user2649947
user2649947

Reputation:

Python reading a .jpg file in binary for beginner

I'm trying to learn more about exif data contained within a photo. What I don't understand is why I get the result from the following code:

file = open("IMG.JPG", "rb")
print(file.read(2))
print(file.read(2))

Gives me a result of:

>>>
b'\xff\xd8'
b'\xff\xe1'

Why are they different? The first result line makes sense, FFD8 represent that its a jpeg.

Upvotes: 1

Views: 6131

Answers (3)

Dan L
Dan L

Reputation: 325

Every time you read() you move the file pointer. If you want to read the same thing repeatedly (why?) then you can use

filename.seek(0)

to rewind the file pointer to the beginning of the file.

Upvotes: 0

aIKid
aIKid

Reputation: 28312

file.read will move on to the next part to read once you call it. If you read it to the end, and call it again, it would return nothing.

For example, i have a file called test.txt, like this:

abcdefg
hijklmn

Let's try to read it:

>>> with open('test.txt') as f:
    data = f.read(7)
    data2 = f.read()


>>> data
'abcdefg'
>>> data2
'\nhijklmn' 

See?

Now, if you want to get the same thing twice, you can make the reading back to the beginning using file.seek:

>>> with open('test.txt') as f:
    data = f.read(7)
    f.seek(0)
    data2 = f.read(7)


>>> data
'abcdefg'
>>> data2
'abcdefg'

Hope this helps!

Upvotes: 1

weemattisnot
weemattisnot

Reputation: 919

It is because each time you call file.read(x) it reads the next x items, not the first x items.

Upvotes: 5

Related Questions