【问题标题】:Can 'file.read() function' not be used twice? [duplicate]'file.read() function' 不能使用两次吗? [复制]
【发布时间】:2019-11-03 08:24:24
【问题描述】:

'file.read() function' 不能用两次吗?

我一开始执行了 file.read() 并且效果很好,但是当我在关闭文件之前尝试使用该函数时它不起作用。

f=open("text.txt","r")
f.read()
'hello\nbye'
f.read()
''

【问题讨论】:

  • 第一次阅读时,文件指针已移至文件末尾。第二次,没有什么可读的了。
  • 阅读文件就像使用书签一样,每次阅读内容时都会从书签开始,并相应地移动书签。如果您想再次阅读某些内容,则必须:将书签移回或以某种方式重新打开文件。

标签: python


【解决方案1】:

第一次阅读时,光标到达文件末尾。使用seek(0)将光标移回文件开头:

In [28]: f=open("test.txt","r")

In [29]: f.read()
Out[29]: 'hello\nbye'

In [30]: f.read()
Out[30]: ''

In [31]: f.seek(0)
Out[31]: 0

In [32]: f.read()
Out[32]: 'hello\nbye'

【讨论】:

    【解决方案2】:

    如果已到达文件末尾,f.read() 将返回一个空字符串 ('')。

    更多信息可以在这里找到:https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

    【讨论】:

      【解决方案3】:

      保存到对象

      with open( "text.txt","r" ) as f :
          file = f.readlines()
      

      并且您将内容存储在“文件”对象中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-16
        • 1970-01-01
        • 2017-02-15
        • 2021-08-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多