Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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?

like image 749
jorrebor Avatar asked Jul 25 '12 14:07

jorrebor


1 Answers

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.

like image 132
jamylak Avatar answered Oct 01 '22 11:10

jamylak