为什么我只能从文件中读取一行?

时间:2012-05-09 19:24:08

标签: python

我有一个包含python对象的文件作为字符串,然后我打开它并像我一样显示:

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

但后来我有问题,因为不再有任何行:

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

为什么会出现这种情况?如何保持对文件行的访问?

4 个答案:

答案 0 :(得分:10)

您在文件中的位置已移动

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()为您提供了该文件的内容列表,您可以反复阅读该列表。最好在读取文件后关闭文件,然后使用从文件中获取的内容。不要一直尝试一遍又一遍地阅读文件内容,你已经知道了。

答案 1 :(得分:9)

该文件中只有一行,您只需阅读它即可。 readlines返回所有行的列表。如果要重新读取文件,则必须执行file.seek(0)

答案 2 :(得分:3)

将结果保存到变量或重新打开文件?

lines = file.readlines()

答案 3 :(得分:2)

您可以将行列表存储在变量中,然后访问它 随时随地:

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