Sheldon
Sheldon

Reputation: 4643

How can I get open() to skip bytes at the beginning of a binary file?

I would like to open time series data written as a binary file using Python 3.5.

Here is the script that I wrote so far:

filename = 'dummy.ats'
file = open(filename, 'rb')

The binary file starts with a header of 1024 bytes that I would like to skip. How can I modify my script to do this?

Upvotes: 5

Views: 12979

Answers (1)

Hearner
Hearner

Reputation: 2729

The function seek() allows you to move the reading cursor where you want in your file (this cursor automatically moves forward when you read something).

It works like :

file.seek(how many positions you will move[,0 or 1 or 2])

( [] <- means optional)

  • 0 (or os.SEEK_SET): means your reference point is the beginning of the file
  • 1 (or os.SEEK_CUR): means your reference point is the current file position
  • 2 (or os.SEEK_END): means your reference point is the end of the file

But you can omit it and it'll be 0

filename = 'dummy.ats'
file = open(filename, 'rb')
file.seek(2)

if you read from there, you'll read from the 2nd character

Upvotes: 11

Related Questions