read a file line by line using readline()

P

Phoe6

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.
 
T

Thomas Girod

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.
 
P

Phoe6

Thomas said:
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 ''. :(
 
B

Bruno Desthuilliers

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()
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top