Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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!

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top