Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python read() function returns empty string [closed]

Tags:

python

file-io

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?

like image 420
Francesco R. Avatar asked May 04 '13 12:05

Francesco R.


People also ask

What does read () return in Python?

Definition and Usage. The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.

How does read () work in Python?

read() method in Python is used to read at most n bytes from the file associated with the given file descriptor. If the end of the file has been reached while reading bytes from the given file descriptor, os. read() method will return an empty bytes object for all bytes left to be read.

How do you fill an empty string in Python?

Strings are immutable in Python, you cannot add to them. You can, however, concatenate two or more strings together to make a third string.


2 Answers

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.

like image 146
pradyunsg Avatar answered Oct 21 '22 22:10

pradyunsg


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.

like image 8
Martijn Pieters Avatar answered Oct 21 '22 22:10

Martijn Pieters