封闭的文件对象该怎么办? [英] What can I do with a closed file object?

查看:61
本文介绍了封闭的文件对象该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打开文件时,文件存储在一个打开的文件对象中,使您可以访问文件上的各种方法,例如读取或写入.

When you open a file, it's stored in an open file object which gives you access to various methods on it such as reading or writing.

>>> f = open("file0")
>>> f
<open file 'file0', mode 'r' at 0x0000000002E51660>

当然,完成后,您应该关闭文件以防止其占用内存空间.

Of course when you're done you should close your file to prevent it taking up memory space.

>>> f.close()
>>> f
<closed file 'file0', mode 'r' at 0x0000000002E51660>

这会留下一个关闭的文件,因此该对象仍然存在,尽管为了可读起见它不再使用空间.但这有实际应用吗?它不能被读取或写入.无法再次使用它重新打开文件.

This leaves a closed file, so that the object still exists though it's no longer using space for the sake of being readable. But is there any practical application of this? It can't be read, or written. It can't be used to reopen the file again.

>>> f.open()

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    f.open()
AttributeError: 'file' object has no attribute 'open'

>>> open(f)

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    open(f)
TypeError: coercing to Unicode: need string or buffer, file found

除了标识已引用文件对象但已关闭文件对象之外,该关闭的文件对象还有实际用途吗?

Is there a practical use for this closed file object aside from identifying that a file object is being referenced but is closed?

推荐答案

一种用途是使用名称重新打开文件:

One use is using the name to reopen the file:

open(f.name).read()

当使用 NamedTemporaryFile 编写更新后的内容,然后将原始文件替换为 shutil.move :

I use the name attribute when changing a file content using a NamedTemporaryFile to write the updated content to then replace the original file with shutil.move:

with open("foo.txt") as f, NamedTemporaryFile("w", dir=".", delete=False) as temp:
    for line in f:
        if stuff:
            temp.write("stuff")

shutil.move(temp.name, "foo.txt")

您也可以使用f.closed来评论该文件是否确实已关闭.

Also as commented you can use the f.closed to see if the file is really closed.

这篇关于封闭的文件对象该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆