read a file line by line using readline()
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Wed Mar 22 19:04:39 EST 2006
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()
More information about the Python-list
mailing list