Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read all but the last X bytes from a binary file?

I want to read all data from a binary file without the last 4 bytes. How can we do it in Python?

like image 823
odi assle Avatar asked May 18 '16 11:05

odi assle


2 Answers

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. :-)

like image 196
catleeball Avatar answered Sep 25 '22 21:09

catleeball


Read it as you normally would, then slice the result:

with open(path_to_file, 'rb') as f:
    f.read()[:-4]
like image 23
DeepSpace Avatar answered Sep 23 '22 21:09

DeepSpace