Beginner question : skips every second line in file when using readline()

Hans Nowak hans at zephyrfalcon.org
Mon Oct 20 00:15:25 EDT 2003


peter leonard wrote:

> Hi,
> I having a problem with reading each line from a text file. For example, 
> the file is a text file named 'test.txt' with the following content :
> 
> line 1
> line 2
> line 3
> line 4
> line 5
> 
> The following script attempts to print out each line :
> 
> datafile ="C:\\Classifier\Data\\test.txt"
> dataobject = open(datafile,"r")
> 
> while dataobject.readline() !="":
> 
>        line = dataobject.readline()
>        print line

You're calling readline() twice.  Use something like:

line = dataobject.readline()
while <line is not empty>:
     ...do stuff...
     line = dataobject.readline()

or:

for line in dataobject:
     if <line is empty>:
         break
     ...do stuff...

I'm writing <line is empty>, because you might want to revise 
dataobject.readline() != "" as well.  If you read from a text file, lines will 
end in \n, so comparing them to "" will always return false.  To check for an 
empty line, not counting the trailing newline, use something like

if not line.rstrip():
     # line is empty

HTH,

-- 
Hans (hans at zephyrfalcon.org)
http://zephyrfalcon.org/







More information about the Python-list mailing list