Remove number of bytes from beginning of file
12,438
Solution 1
f = open('filename.ext', 'rb')
f.seek(255) # skip the first 255 bytes
rest = f.read() # read rest
Solution 2
with open('input', 'rb') as in_file:
with open('output', 'wb') as out_file:
out_file.write(in_file.read()[256:])
Solution 3
Use seek
to skip the first 256 bytes, then copy the file in chunks to avoid reading the entire input file into memory. Also, make sure to use with
so that the file is closed properly:
with open('input.dat', 'rb') as inFile:
inFile.seek(256)
with open('output.dat', 'wb') as outFile:
for chunk in iter(lambda: inFile.read(16384), ''):
outFile.write(chunk)
Author by
ZoRo
Updated on June 07, 2022Comments
-
ZoRo almost 2 years
I want to copy a file without the first 256 bytes.
Is there a nice way to do it in python?
I guessing that the simple way is to read byte-byte with a counter and then start copy only when it get to 256.
I was hoping for more elegant way.
Thanks.
-
Ajasja over 4 yearsNote that in python 3 you have to do
b''
otherwise the copy will not finish.