【问题标题】:How do you know when to close a file in python?你怎么知道什么时候在python中关闭文件?
【发布时间】:2017-02-10 09:34:31
【问题描述】:
from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)


in_file = open(from_file)
indata = in_file.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)
#above is the original code. 

他关闭了上面的文件。但是在常见的学生问题中,有这个。

问。当我尝试缩短此脚本时,在最后关闭文件时出现错误。

A.你可能做了这样的事情,indata = open(from_file).read(),这意味着当你到达脚本末尾时你不需要再做 in_file.close()。一旦一行运行,它应该已经被 Python 关闭了。

那么,你怎么知道什么时候关闭文件,什么时候不关闭?

谢谢大家,我明白了! :)

【问题讨论】:

  • indata = in_file.read()之后可以直接关闭文件
  • 无论如何你都应该使用with 构造。
  • 您可以在不再需要读取文件时关闭文件,写入文件?对吗?
  • 这种事情推荐:indata = open(from_file).read()。详情请见here。正如那个答案所说,您应该使用with 打开文件,例如with open(from_file) as indata:

标签: python


【解决方案1】:

来自methods-of-file-objects

在处理文件对象时最好使用 with 关键字。这样做的好处是文件在其套件后正确关闭 完成,即使在途中引发了异常。它也比编写等效的 try-finally 块要短得多:

>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

【讨论】:

    【解决方案2】:

    何时关闭文件?总是 - 一旦你完成了它的工作。否则只会占用内存。

    【讨论】:

    • 没错,但最安全和最干净的方法是使用with,而不是自己显式调用文件的.close 方法。
    猜你喜欢
    • 2011-08-08
    • 2010-09-10
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 2010-11-29
    • 2018-01-21
    • 2011-11-05
    • 1970-01-01
    相关资源
    最近更新 更多