Writing Binary Files in Python 3.x

  • Python
  • Thread starter chaoticflow
  • Start date
  • #1
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.
 

Answers and Replies

  • #2
66
24
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
34,005
5,660
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
66
24
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
34,005
5,660
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.
 

Related Threads on Writing Binary Files in Python 3.x

Replies
9
Views
16K
Replies
3
Views
4K
  • Last Post
Replies
4
Views
1K
  • Last Post
Replies
1
Views
21K
  • Last Post
Replies
6
Views
2K
Replies
1
Views
15K
Replies
5
Views
2K
  • Last Post
Replies
3
Views
4K
  • Last Post
Replies
1
Views
2K
Replies
6
Views
4K
Top