Why read()
returns an empty string when it reaches the end of the file; this empty string shows up as a blank line. I know we can remove it using rstrip()
.
Asked
Active
Viewed 2,134 times
0

cyzczy
- 197
- 1
- 2
- 11
-
1http://stackoverflow.com/questions/16374425/python-read-function-returns-empty-string – Harsha W May 08 '17 at 09:36
-
4It returns an empty string at the end of a file because there's no text at the end of the file – Nick is tired May 08 '17 at 09:38
-
Possible duplicate of [Python read() function returns empty string](http://stackoverflow.com/questions/16374425/python-read-function-returns-empty-string) – WhatsThePoint May 08 '17 at 09:45
2 Answers
1
read() method returns empty string because you have reach end of the file and there is no more text in the file.
f = open('f.txt')
print f.read()
print f.tell()
Here f.tell() will give you the seek position and when you do f.tell() it would be at the end of file and returns the length of the file.

bigbounty
- 16,526
- 5
- 37
- 65
0
I have had this problem for a while and, I have been looking for the answer to this question. I recently found the solution.
You must set the .read()
to a string
This will work :
read_file = open("file.txt", "r")
file_string = read_file.read()
print(file_string)
read_file.close()
I Hope this helps. It worked for me, so I am confident it will work for you.