I want to read all data from a binary file without the last 4 bytes. How can we do it in Python?
This question is old, but for others who find this on Google, please note: doing f.read()[:-4]
will read the whole file into memory, then slice it.
If you only need the first N bytes of a file, simply pass the size to the read()
function as an argument:
with open(path_to_file, 'rb') as f:
first_four = f.read(4)
This avoids reading an entire potentially large file when you could lazily read the first N bytes and stop.
If you need the last N bytes of a file, you can seek to the last block of the file with os.lseek()
. This is more complicated and left as an exercise for the reader. :-)
Read it as you normally would, then slice the result:
with open(path_to_file, 'rb') as f:
f.read()[:-4]
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