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

krz*_*hub 6 python

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

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

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

>>> f.readlines()
[]
>>> f.readline(0)
''
Run Code Online (Sandbox Code Playgroud)

为什么它是heppening,我如何保持访问文件的行?

Ver*_*non 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
Run Code Online (Sandbox Code Playgroud)

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


Ste*_*ini 9

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