Python read() function returns empty string [closed]

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.

Leave a Comment