krzyhub
krzyhub

Reputation: 6540

Why can i read lines from file only one time?

I have a file containing python's object as string, then i open it and doing things like i showing:

>>> file = open('gods.txt')
>>> file.readlines()
["{'brahman': 'impersonal', 'wishnu': 'personal, immortal', 'brahma': 'personal, mortal'}\n"]

But then i have problem because there is no longer any lines:

>>> f.readlines()
[]
>>> f.readline(0)
''

Why it is heppening and how can i stay with access to file's lines?

Upvotes: 7

Views: 5096

Answers (4)

Vernon
Vernon

Reputation: 2783

Your position in the file has moved

f = open("/home/usr/stuff", "r")
f.tell()
# shows you're at the start of the file
l = f.readlines()
f.tell()
# now shows your file position is at the end of the file

readlines() gives you a list of contents of the file, and you can read that list over and over. It's good practice to close the file after reading it, and then use the contents you've got from the file. Don't keep trying to read the file contents over and over, you've already got it.

Upvotes: 10

Thanasis Petsas
Thanasis Petsas

Reputation: 4448

You can store the lines list in a variable and then access it whenever you want:

file = open('gods.txt')
# store the lines list in a variable
lines = file.readlines()
# then you can iterate the list whenever you want
for line in lines:
  print line

Upvotes: 2

Stefano Borini
Stefano Borini

Reputation: 143855

There's only one line in that file, and you just read it. readlines returns a list of all the lines. If you want to re-read the file, you have to do file.seek(0)

Upvotes: 11

Mattias Isegran Bergander
Mattias Isegran Bergander

Reputation: 11909

save the result to a variable or reopen the file?

lines = file.readlines()

Upvotes: 3

Related Questions