Writing Binary Files in Python 3.x

In summary, the bin function in Python 3 can read and write binary files. However, to read the contents of a binary file, you must use the struct module. To write a binary file, you must use the pack and unpack operations.
  • #1
chaoticflow
8
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
  • #2
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.
 
  • #3
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 FactChecker
  • #4
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.
 
  • #5
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.
 

FAQ: Writing Binary Files in Python 3.x

How do I open a binary file in Python 3.x?

To open a binary file in Python 3.x, you can use the built-in open() function. The open() function takes two parameters: the file name and the mode in which you want to open the file. To open a file in binary mode, you can specify the mode as 'rb', which stands for "read binary".

How do I read from a binary file in Python 3.x?

Once you have opened a binary file in Python 3.x, you can use the read() method to read the contents of the file. The read() method takes in a number as a parameter, which specifies the number of bytes to be read from the file. If no parameter is provided, the entire file is read. The read() method returns the data as a string of bytes.

How do I write to a binary file in Python 3.x?

To write to a binary file in Python 3.x, you can use the write() method. The write() method takes in a string of bytes as a parameter and writes it to the file. You can also use the writelines() method to write multiple lines of data to the file at once.

How do I close a binary file in Python 3.x?

It is important to close a file after you have finished reading from or writing to it in Python 3.x. To close a binary file, you can use the close() method on the file object. This will ensure that all data is written to the file and the file resources are released.

How do I handle errors when working with binary files in Python 3.x?

When working with binary files in Python 3.x, it is important to handle errors that may occur. You can use try/except blocks to catch and handle any errors that may occur while opening, reading, or writing to a binary file. It is also recommended to use the with statement when working with files, as it automatically handles closing the file for you, even in the case of an error.

Similar threads

Back
Top