python3 file.readline EOF?

Viewed 18041

I am having trouble determining when I have reached the end of a file in python with file.readline

fi = open('myfile.txt', 'r')
line = fi.readline()
if line == EOF:  //or something similar
    dosomething()

c = fp.read() if c is None: will not work because then I will loose data on the next line, and if a line only has a carriage return I will miss an empty line.

I have looked a dozens or related posts, and they all just use the inherent loops that just break when they are done. I am not looping so this doesn't work for me. Also I have file sizes in the GB with 100's of thousands of lines. A script could spend days processing a file. So I need to know how to tell when I am at the end of the file in python3. Any help is appreciated. Thank you!

5 Answers

The simplest way to check whether you've reached EOF with fi.readline() is to check the truthiness of the return value;

line = fi.readline()
if not line:
    dosomething() # EOF reached

Reasoning

According to the official documentation

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

and the only falsy string in python is the empty string ('').

Related