Why do I need to assign the variable f.readlines () to get its length?

If I do this:

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 result to be the same, but it is not:

without assignment 0
with assigment     1268

Why is this?

+5
source share
1 answer

The file object is fan iterator over the lines of the file. f.readlines()moves the cursor to the end, but stores the lines in lines, so the second example works for you. The first example does not work because you have reached the end of the file and there are no lines to read. You can use f.seek(0)to move the cursor back to the beginning of the file if you want to do this job.

+7
source

All Articles