-2

When I open a text file in python to read it, the first time I call f.read() it works fine but any subsequent calls it returns an empty string (''). Even using it again in a single line will change it to the blank string.

The text I'm reading is a random collection of unicode characters between 0 and 128, if that helps.

for example:

>>> f = open("Data.txt")
>>> f.read() 
'$$$\x00\x00\x11$$$'
>>> f.read() 
''
>>> f.close()

What's causing this and how do I fix it?

FaceySmile
  • 53
  • 9
  • 1
    The `read()` method moves the file pointer forwards, and (likely) in this case, to the end of the file. Where there is nothing to read. You can move the file pointer to the beginning again using `f.seek(0)`, and then read (the same) data again. –  Sep 02 '15 at 01:47
  • Thanks, I'm surprised I've only just come across that. – FaceySmile Sep 02 '15 at 01:51
  • Definitely a duplicate Evert, I did look but obviously not hard enough. – FaceySmile Sep 02 '15 at 01:53

1 Answers1

1

It is actually the expected behavior and documented in the official documentation:

...

If the end of the file has been reached, f.read() will return an empty string ("").

It explicitly gives the same example with yours:

>>> f.read()
'This is the entire file.\n'
>>> f.read()
''

You can reset the file pointer by calling seek():

file.seek(0)

So, in your case, it will be:

>>> f = open("Data.txt")
>>> f.read() 
'$$$\x00\x00\x11$$$'
>>> f.read() 
''
>>> f.seek(0) # move the pointer to the beginning of the file again
>>> f.read() 
'$$$\x00\x00\x11$$$'
>>> f.close()
Sait
  • 19,045
  • 18
  • 72
  • 99