471,091 Members | 1,526 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,091 software developers and data experts.

read a file line by line using readline()

Hi all,
I just read the manual and got to know I can use a for loop to iterate
through the lines in the file.

But so far, I was strugling with the following:

import os
file = open('File1.txt','r')
line = file.readline()
while line !=' ':
print line
line = file.readline()

As mentioned in the docs, the EOF returns an empty string. I am unable
to catch or match against the EOF. Please help me in pointing out as
where I am making the mistake.
--
Senthil
http://phoe6.livejournal.com

Mar 22 '06 #1
3 8508
If your code is exactly what you've copy-pasted, then you are not
testing against an empty string but a "one blank space" string ...

I've just tried with :

while line != "":

and it works very well.

Mar 22 '06 #2
Thomas Girod wrote:

while line != "":

and it works very well.


Thanks Thomas, I stand corrected now.
my mistake, I was checking against a single space ' ' instead of empty
string ''. :(

--
Senthil

Mar 22 '06 #3
Phoe6 a écrit :
Hi all,
I just read the manual and got to know I can use a for loop to iterate
through the lines in the file.

But so far, I was strugling with the following:

import os
file = open('File1.txt','r')
'file' is the builtin type for file objects (like the one returned by
open()). Avoid using it as an identifier, this shadows the file type.
line = file.readline()
while line !=' ':
As Thomas pointed out, this is not an empty string !-)

Also, this is not a for loop...
print line
line = file.readline()


Do yourself a favor, use a for loop. Also, a file opened in read mode is
already an iterator :

f = open('path/to/file')
for line in f:
do_something_with(line)
f.close()

Mar 22 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

18 posts views Thread by jas | last post: by
31 posts views Thread by microsoft.news.com | last post: by
2 posts views Thread by CsharpGuy | last post: by
11 posts views Thread by jo3c | last post: by
5 posts views Thread by dm3281 | last post: by
6 posts views Thread by Sean Davis | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.