Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create binary file in python

I have a very large binary file called file1.bin and I want to create a file, file2.bin, that holds only the first 32kb of file1.bin.

So I'm reading file1 as follows:

myArr = bytearray()

with open(r"C:\Users\User\file1.bin", "rb") as f:
byte = f.read(1)
for i in range(32,678):
    myArr.extend(byte)
    byte = f.read(1)

My question is: How do I proceed from here to create the file2 binary file out of myArr?

I tried

with open(r"C:\Users\User\file2.bin", "w") as f:
f.write(myArr)

but this results in:

f.write(myArr)
TypeError: must be string or pinned buffer, not bytearray
like image 716
Subway Avatar asked Mar 20 '23 12:03

Subway


1 Answers

You need to open the file in binary write mode (wb).

with open('file2.bin', 'wb') as f:
    f.write(myArr)

Also, the way you are reading from the input file is pretty inefficient. f.read() allows you to read more than one byte at a time:

with open('file1.bin', 'rb') as f:
    myArr = bytearray(f.read(32678))

Will do exactly what you want.

like image 90
Joel Cornett Avatar answered Mar 23 '23 01:03

Joel Cornett