Reputation: 5726
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
Upvotes: 5
Views: 56146
Reputation: 1943
Open files with appropriate flags, then read from one in blocks of 1024 bytes and write to other, if less than 1024 bytes are remaining, copy byte-wise.
fin = open('file1.bin', 'rb')
fout = open('file2.bin', 'w+b')
while True:
b=fin.read(1024)
if b:
n = fout.write(b)
else:
while True:
b=fin.read(1)
if b:
n=fout.write(b)
else:
break
break
Upvotes: 0
Reputation: 24788
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.
Upvotes: 10