如何重新打开已关闭的文件?

2024-04-26 23:09:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个打开时使用的文件对象file

with open("text.txt","rb") as file:
    # read some line

file.write("texte")  # I know that doesn't work

我只是想知道我是否可以再次打开这个文件,因为Python有关于它的所有信息,但它说这个文件已关闭。 我正在尝试读取文件中的一些行,最后,我将在文件末尾写一行新行,因此我想以追加模式重新打开此文件

>>> with open("test.txt","wb") as fich:
...     fich.write("test In ")
...
>>> fich
<closed file 'test.txt', mode ‘wb' at 0x7f3f49a3a4b0>
>>> fich.open
Traceback (most recent call last):
  File “<stdin>", line 1, in <module>

我正在调用一个以文件句柄为参数的函数,因此我不能第一次重用open,因为函数中的文件名是未知的

我可以重新打开把手吗?因为我可以使用相同的方法重新打开它:

with open("filename") as anotherfile:

Tags: 文件对象函数texttesttxtaswith
1条回答
网友
1楼 · 发布于 2024-04-26 23:09:07

非常简单:重新打开文件:

with open("text.txt","r") as file:
    #read some line

with open(file.name,"a") as file:
    file.write("texte") # now it works

现在你在评论中提到:

i am passing this file handle as parameter in a function call , so the filename isn't known inside the function, so reopening the file with the same method is impossible inside the function , that"s why i'm asking how to reopen the file handle

现在事情变得一团糟了。一般规则是,函数不应关闭/重新打开其调用者提供的资源,即:

def foo(fname):
    with open(fname) a file:
       bar(file)

def bar(file):
   file.close()
   with open(file.name, "a") as f2:
      f2.write("...")

这是一种糟糕的做法-此处bar不应关闭文件,只应使用它-处理文件是foo(或调用bar的人)的职责。因此,如果您需要这样一种模式,那么您的设计有问题,您最好先修复您的设计

请注意,您可以在不关闭第一个句柄的情况下打开要追加的文件:

def bar(file):
   with open(file.name, "a") as f2:
      f2.write("...")

但这仍可能打乱来电者的预期

相关问题 更多 >