Beginner question : skips every second line in file when using readline()
peter leonard
pfleonard at hotmail.com
Mon Oct 20 00:40:27 EDT 2003
Thanks for point out my error. This works fine now :
datafile ="C:\\Classifier\Data\\test.txt"
dataobject = open(datafile,"r")
line = dataobject.readline()
while line.strip():
print line
line = dataobject.readline()
I get the following desired output :
line 1
line 2
line 3
line 4
line 5
Thanks again
Peter
>From: Hans Nowak <hans at zephyrfalcon.org>
>To: peter leonard <pfleonard at hotmail.com>
>Subject: Re: Beginner question : skips every second line in file when using
> readline()
>Date: Mon, 20 Oct 2003 00:15:25 -0400
>
>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/
>
_________________________________________________________________
Fretting that your Hotmail account may expire because you forgot to sign in
enough? Get Hotmail Extra Storage today!
http://join.msn.com/?PAGE=features/es
More information about the Python-list
mailing list