How do I tell the difference between the end of a text file, and an empty line in a text file?

Steven Bethard steven.bethard at gmail.com
Wed May 16 23:15:38 EDT 2007


walterbyrd wrote:
> Python's lack of an EOF character is giving me a hard time.
> 
> I've tried:
> 
> -----
> s = f.readline()
> while s:
> .
> .
> s = f.readline()
> --------
> 
> and
> 
> -------
> s = f.readline()
> while s != ''
> .
> .
> s = f.readline()
> -------
> 
> 
> In both cases, the loop ends as soon it encounters an empty line in
> the file, i.e.

That's just not true.  Did you try that code?

 >>> open('temp.txt', 'w').write('''\
... xxxxxxxxxx
... xxxxxxxxxxx
... xxxxxxx
...
... xxxxxxxxxxxxxx
... xxxxxxxxxx
... x
... ''')
 >>> while s:
...     print s,
...     s = f.readline()
...
 >>> f = open('temp.txt')
 >>> s = f.readline()
 >>> while s:
...     print s,
...     s = f.readline()
...
xxxxxxxxxx
xxxxxxxxxxx
xxxxxxx

xxxxxxxxxxxxxx
xxxxxxxxxx
x

The file.readline() method returns '\n' for empty lines and '' for 
end-of-file.

STeVe



More information about the Python-list mailing list