【问题标题】:Why can i read lines from file only one time?为什么我只能从文件中读取行一次?
【发布时间】:2012-05-18 08:42:10
【问题描述】:

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

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

但是我遇到了问题,因为不再有任何线条:

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

为什么会发生这种情况,我如何才能继续访问文件行?

【问题讨论】:

  • file.readlines() 为您提供文件中的行列表,但它会读取整个文件。将其保存到变量中? contents = file.readlines()?
  • 您可以使用seek(0)重置到文件开头
  • 为什么 file.readlines() 自然只能使用一次?

标签: python


【解决方案1】:

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

【讨论】:

  • 感谢您提供这些实用知识。
【解决方案2】:

您在文件中的位置已移动

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() 为您提供文件内容列表,您可以一遍又一遍地阅读该列表。读取文件后关闭文件,然后使用从文件中获得的内容是一种很好的做法。不要一遍又一遍地尝试读取文件内容,您已经掌握了。

【讨论】:

  • 这正是我需要知道的。谢谢。
【解决方案3】:

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

lines = file.readlines()

【讨论】:

    【解决方案4】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-08
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      • 2012-12-21
      相关资源
      最近更新 更多