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

P

peter leonard

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

However, the output from this script is :

line 2

line 4


I'm sure this is a simple problem but I can't figure it after loking up
several reference books and web pages. Any help would be greatly
appreciated.

Regards
Peter

_________________________________________________________________
Want to check if your PC is virus-infected? Get a FREE computer virus scan
online from McAfee.
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963
 
J

Jules Dubois

On Sun, 19 Oct 2003 20:33:49 -0700, in article
while dataobject.readline() !="":

line = dataobject.readline()
print line

However, the output from this script is :

line 2

line 4

You're reading a line in the "while:" statement by calling readline(), but
the line being read isn't used. Then, you call readline() again in the
body of the loop. That's the only input you're going to see in your
output, the even-numbered lines.

Do something like this instead:

for line in dataobject.xreadlines():
print line

I'm no Python expert, so there may be a better way. The code above works
for me.
 
B

Ben Finney

while dataobject.readline() !="":

Reads the next line, compares it to the empty string, then throws it
away.
line = dataobject.readline()

Reads the next line and assigns it to the 'line' variable.
print line

Prints out the 'line' variable.

I think you can see where the problem is.

Possibly you want something like this:

while( True ):
line = dataobject.readline()
if( line == "" ):
break
print line
 
R

Roy Smith

peter leonard said:
datafile ="C:\\Classifier\Data\\test.txt"
dataobject = open(datafile,"r")

while dataobject.readline() !="":

line = dataobject.readline()
print line

The basic problem is that you're calling readline() twice each time
around the loop. Once in the test part of the while (where you test and
then throw away the returned value), and again in the body. Of course
you're only getting every other line! You want to do something like
this:

while 1:
line = dataobject.readline()
if line == "":
break
print line
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top