Reputation: 131
If we consider
f=open('foo.txt')
x= f.readline()
print x
Then we get the first line of file foo.txt.
Now consider:
<code>
f=open('foo.txt')
while (x = f.readline()) != '': # Read one line till EOF and do something
.... do something
f.close()
</code>
This gives a syntax error at
x=f.readline().
I am relatively new to Python and I cannot figure out the problem. One encounters this kind of expression often in C.
Thanks in advance
Upvotes: 0
Views: 739
Reputation: 51
I guess you have answer here What's perfect counterpart in Python for "while not eof"
In short you can check whether line is still valid on each loop like this
with open(filename,'rb') as f:
while True:
line=f.readline()
if not line: break
process(line)
Or you can use python built in function to iterate over file like this
with open('file') as myFile:
for line in myFile:
do_something()
Upvotes: 1