Newbie: Reading textfiles

ze luis.amoreira at netc.pt
Wed Mar 1 17:12:04 EST 2000


Hello!
"Lutz Schröer" wrote:

> Hi,
>
> after looking for a"clever" solution for reading a text file line by line
> from the beginning to the end for the whole day, I have to ask this
> ridiculous newbie question:
>
> How do I read a textfile line by line and catch the eof?
>
> Latz

How clever would you like it? This one is straight from the standard
tutorial, Chapter 7. Say you want to read from a file named "file.txt", and
print each line. Just do:

input=open('file.txt','r')         #open file.txt for reading
while 1:
   newline = input.readline()    #read a line
   if newline == '': break         #is it empty? you've hit eof. stop reading

   print newline                       #else, print the line

I hope it helps.
Ze Amoreira,
amoreira at mercury.ubi.pt




More information about the Python-list mailing list