【问题标题】:How opened file cannot be rewind by seek(0) after using with open() in python在 python 中使用 with open() 后如何通过 seek(0) 倒回打开的文件
【发布时间】:2017-10-13 18:10:49
【问题描述】:

当我试图在 python 中逐行打印文件内容时,如果文件是由 with open("file_name") as f: 但是,如果我使用 open("file_name") as f: 就可以做到这一点 然后 f.seek(0)

以下是我的代码

with open("130.txt", "r") as f:             #f is a FILE object
    print (f.read())                        #so f has method: read(), and f.read() will contain the newline each time 

f.seek(0)                             #This will Error!
with open("130.txt", "r") as f:       #Have to open it again, and I'm aware the indentation should change  
for line in f:                    
    print (line, end="")          

f = open("130.txt", "r")
f.seek(0)
for line in f:
    print(line, end="")

f.seek(0)                           #This time OK!
for line in f:
    print(line, end="")

我是python初学者,谁能告诉我为什么?

【问题讨论】:

    标签: python file seek


    【解决方案1】:

    第一个f.seek(0)会抛出错误,因为

    with open("130.txt", "r") as f:
        print (f.read())
    

    将在块的末尾关闭文件(一旦文件被打印出来)

    您需要执行以下操作:

    with open("130.txt", "r") as f:
        print (f.read())
    
        # in with block
        f.seek(0)
    

    【讨论】:

      【解决方案2】:

      with 的目的是在块结束时清理资源,在这种情况下包括关闭文件句柄。

      您应该可以像这样在with 块内.seek

      with open('130.txt','r') as f:
        print (f.read())
      
        f.seek(0)
        for line in f:
          print (line,end='')
      

      根据您的评论,with 在这种情况下是这样的语法糖:

      f = open(...)
      try:
        # use f
      finally:
        f.close()
      
      # f is still in scope, but the file handle it references has been closed
      

      【讨论】:

      • 谢谢!第一个 FILE 对象 f 是否消失?使用 type(f) 我得到: 似乎它仍然存在。我很难切换到 python。
      • f 仍然存在并将引用文件句柄周围的包装器,但它实际包装的句柄将已关闭,因此当进行后续调用时它们将失败。我当然希望f 的范围为with 块,但Python 在这种事情上相当松散。
      • 我明白了,处理程序还在,但它包装的内容已经关闭。问题解决!非常感谢!
      猜你喜欢
      • 2011-06-04
      • 2012-03-06
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 2020-10-25
      • 2014-03-07
      • 2014-01-15
      相关资源
      最近更新 更多