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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With