odi assle
odi assle

Reputation: 211

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?

Upvotes: 10

Views: 24452

Answers (2)

DeepSpace
DeepSpace

Reputation: 81604

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

with open(path_to_file, 'rb') as f:
    f.read()[:-4]

Upvotes: 4

catleeball
catleeball

Reputation: 871

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

Upvotes: 51

Related Questions