Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "readlines()" twice in a row [duplicate]

I'm trying to do something like this:

Lines = file.readlines()
# do something
Lines = file.readlines()  

but the second time Lines is empty. Is that normal?

like image 776
Bob Avatar asked Apr 18 '12 00:04

Bob


2 Answers

You need to reset the file pointer using

file.seek(0)

before using

file.readlines()

again.

like image 163
houbysoft Avatar answered Nov 10 '22 19:11

houbysoft


Yes, because .readlines() advances the file pointer to the end of the file.

Why not just store a copy of the lines in a variable?

file_lines = file.readlines()
Lines = list(file_lines)
# do something that modifies Lines
Lines = list(file_lines)

It'd be far more efficient than hitting the disk twice. (Note that the list() call is necessary to create a copy of the list so that modifications to Lines won't affect file_lines.)

like image 11
Amber Avatar answered Nov 10 '22 19:11

Amber