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().
-
1stackoverflow.com/questions/16374425/…Harsha W– Harsha W2017-05-08 09:36:52 +00:00Commented May 8, 2017 at 9:36
-
4It returns an empty string at the end of a file because there's no text at the end of the fileNick is tired– Nick is tired2017-05-08 09:38:36 +00:00Commented May 8, 2017 at 9:38
-
Possible duplicate of Python read() function returns empty stringWhatsThePoint– WhatsThePoint2017-05-08 09:45:28 +00:00Commented May 8, 2017 at 9:45
Add a comment
|
2 Answers
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.
Comments
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.