0

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

DBS
  • 131
  • 5
  • 1
    In Python, as assignment is not an expression and can not be used in a condition. What exactly do you want to achieve with this? Have you tried just `for x in f:`? – tobias_k May 20 '15 at 10:15
  • yes I know about `for x in f:` but I just wanted to see if a C like construction works out or not. The expression versus assignment clarifies it. Than you! – DBS May 20 '15 at 18:44

1 Answers1

1

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()
Community
  • 1
  • 1
Lukasz
  • 51
  • 5