簡體   English   中英

為什么我只能從文件中讀取一行?

[英]Why can i read lines from file only one time?

我有一個包含python的對象作為字符串的文件,然后我打開它並做像我顯示的事情:

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

但后來我有問題,因為不再有任何行:

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

為什么它是heppening,我如何保持訪問文件的行?

您在文件中的位置已移動

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()為您提供文件內容列表,您可以反復閱讀該列表。 最好在讀取文件后關閉文件,然后使用從文件中獲取的內容。 不要一直嘗試一遍又一遍地閱讀文件內容,你已經知道了。

該文件中只有一行,您只需閱讀它即可。 readlines返回所有行的列表。 如果要重新讀取文件,則必須執行file.seek(0)

將結果保存到變量或重新打開文件?

lines = file.readlines()

您可以將行列表存儲在變量中,然后隨時訪問它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM