14

If I type this in Python:

open("file","r").read()

sometimes it returns the exact content of the file as a string, some other times it returns an empty string (even if the file is not empty). Can someone explain what does this depend on?

4
  • @Pavel Anossov I know that. The same thing happens if i do: f=open("file","r"); f.read() Commented May 4, 2013 at 12:49
  • 1
    @FrancescoR. Then the file is empty. Otherwise provide some code and file contents that we can use to reproduce your problem. Commented May 4, 2013 at 12:52
  • 3
    i checked the files i had used and they were all empty. sorry, my mistake Commented May 4, 2013 at 13:03
  • Duplicate of stackoverflow.com/questions/3906137/… Commented Mar 19, 2022 at 11:26

3 Answers 3

39

When you reach the end of file (EOF) , the .read method returns '', as there is no more data to read.

>>> f = open('my_file.txt')
>>> f.read() # you read the entire file
'My File has data.'
>>> f.read() # you've reached the end of the file 
''
>>> f.tell() # give my current position at file
17
>>> f.seek(0) # Go back to the starting position
>>> f.read() # and read the file again
'My File has data.'

Doc links: read() tell() seek()

Note: If this happens at the first time you read the file, check that the file is not empty. If it's not try putting file.seek(0) before the read.

Sign up to request clarification or add additional context in comments.

1 Comment

i checked the files i had used and they were all empty. sorry, my mistake
9

From the file.read() method documentation:

An empty string is returned when EOF is encountered immediately.

You have hit the end of the file object, there is no more data to read. Files maintain a 'current position', a pointer into the file data, that starts at 0 and is incremented as you read dada.

See the file.tell() method to read out that position, and the file.seek() method to change it.

Comments

3

There is another issue, and that is that the file itself might be leaked and only reclaimed late or even never by the garbage collector. Therefore, use a with-statement:

with open(...) as file:
    data = file.read()

This is hard to digest for anyone with a C-ish background (C, C++, Java, C# and probably others) because the indention there always creates a new scope and any variables declared in that scope is inaccessible to the outside. In Python this is simply not the case, but you have to get used to this style first...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.