Writing Binary Files in Python 3.x

Click For Summary

Discussion Overview

The discussion revolves around writing binary files in Python 3.x, focusing on methods for reading and writing binary data. Participants explore code examples, address misunderstandings, and provide suggestions for using appropriate libraries.

Discussion Character

  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant seeks a simple method to write binary files in Python 3 and shares their initial code attempt.
  • Another participant points out a misunderstanding regarding the built-in bin function and suggests using the struct module for encoding integers.
  • A third participant provides a code example that demonstrates how to pack a list of integers into a binary file using the struct module, including both writing and reading operations.
  • Concerns are raised about naming variables, specifically using 'list', which can mask the built-in type in Python.
  • It is noted that explicit file closing is unnecessary when using a context manager, as the file will be closed automatically.

Areas of Agreement / Disagreement

Participants generally agree on the importance of using the struct module for binary file operations, but there are differing views on the initial code approach and variable naming conventions. The discussion remains unresolved regarding the best practices for writing binary files.

Contextual Notes

Some limitations include potential misunderstandings of the bin function and the implications of variable naming on built-in types. The discussion does not resolve these issues.

chaoticflow
Messages
8
Reaction score
0
Hi,

I've been trying to write a simple binary file in Python 3 and have not yet been able to find a clear answer / solution online.

Could you please suggest a simple way to read / write binary files in Python 3?

My Code:

Code:
# Create Binary File

def dec_base(k,b=2):
    """ Default base is 2 """
    num = ""
    while k:
        num +=str(k%b)
        k = k//2
    return int(num)

test_list = []
for i in range(10):
    test_list.append(dec_base(i))
 
with open("test.bin", "wb") as f:
    for i in test_list:
        f.write(bin(int(i)))

Any help is appreciated.
 
Technology news on Phys.org
You have misunderstood the builtin bin function. Print its output to the console to see what it does. If you must write ints to a binary file, you wil need to choose an encoding. Use the struct module.
 
The following code creates and initializes a list object (numList), and then packs it into a struct named buf. The code writes the struct to a file opened in binary mode, and closes the file.

After that, the code reopens the file, reads the contents, and unpacks the contents into a list. After printing the list, the code closes the file again.

In the pack and unpack operations, the "10i" string is a format string used to pack or unpack the 10 integer values.
Python:
import struct

numList = []
with open("test.bin", "wb") as f:
   for i in range(10):
      numList.append(i)

   buf = struct.pack( "10i",  *numList)
   f.write(buf)
   f.close()

with open("test.bin", "rb") as f:
   f.read(-1)
   list = struct.unpack("10i", buf)
   print(numList)
   f.close()
 
Last edited:
  • Like
Likes   Reactions: FactChecker
Note that calling your list 'list' will mask the builtin type. Also note that explicit closing of the file is unnecessary within the with context manager. The file object's __exit__ method will close the file.
 
Integrand said:
Note that calling your list 'list' will mask the builtin type.
Which I didn't intend to do. I have edited my code to use a different variable name.
Integrand said:
Also note that explicit closing of the file is unnecessary within the with context manager. The file object's __exit__ method will close the file.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
Replies
55
Views
7K
  • · Replies 34 ·
2
Replies
34
Views
6K
Replies
3
Views
3K
  • · Replies 47 ·
2
Replies
47
Views
4K
  • · Replies 57 ·
2
Replies
57
Views
6K
  • · Replies 28 ·
Replies
28
Views
5K
Replies
4
Views
2K
  • · Replies 12 ·
Replies
12
Views
9K
  • · Replies 43 ·
2
Replies
43
Views
5K