6

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Bob
  • 10,741
  • 27
  • 89
  • 143

3 Answers3

13

You need to reset the file pointer using

file.seek(0)

before using

file.readlines()

again.

houbysoft
  • 32,532
  • 24
  • 103
  • 156
11

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.)

Amber
  • 507,862
  • 82
  • 626
  • 550
  • 2
    Your technique here sets `Lines` to the same Python object as `file_lines`. Anything that mutates one would mutate the other for they are the same object. To really be safe, you need to do `lines = file_lines[:]` or in some other way make an actual copy. By the way, the PEP 8 standard suggests using lower-case for variable names, and reserving mixed-case for classes, so I suggest changing `Lines` to just `lines`. – steveha Apr 18 '12 at 00:22
  • @steveha - I already added `list()` calls. As for the variable name, I was simply re-using the OP's name to make it easier for them to read. I agree with you that lower-case is generally better. – Amber Apr 18 '12 at 00:23
  • My apologies. I'm not sure how I missed the `list()` wrapper but I did. Sorry about that. – steveha Apr 18 '12 at 01:28
0

In order to not have to reset every time by using seek method again and again, use the readlines method, but you must store it in variable like this example below:

%%writefile test.txt
this is a test file!
#open it
op_file = open('test.txt')
#read the file
re_file = op_file.readlines()
re_file
#output
['this is a test file!']
# the output still the same
re_file
['this is a test file!']
json25
  • 151
  • 1
  • 3