If I do:
os.chdir(path)
f = open(file,"r")
lines = f.readlines()
print "without assignment " + str(len(f.readlines()))
print "with assignment " + str(len(lines))
I would expect the output the be the same, but it's not:
without assignment 0
with assigment 1268
Why is this?
The file object f
is an iterator over the lines of the file. f.readlines()
moves the file cursor to the end but saves the lines in lines
which is why the second example works for you. The first example doesn't work because you have reached the end of the file and there are no lines left to read. You could use f.seek(0)
to move the cursor back to the beginning of the file if you wanted to make this work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With