Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何知道在python中何时关闭文件?_Python - Fatal编程技术网

如何知道在python中何时关闭文件?

如何知道在python中何时关闭文件?,python,Python,他关闭上面的文件。但是,在普通的学生问题中,有这样一个问题 当我试图缩短这个脚本时,当我在最后关闭文件时会出现一个错误 答:您可能做了类似的操作,indata=open(from_file).read(),这意味着当您到达脚本末尾时,不需要再执行in_file.close()操作。一旦有一行运行,Python应该已经关闭了它 那么,您如何知道何时关闭文件以及何时不关闭 谢谢大家,我明白了!:) 何时关闭文件?总是-一旦你完成了它的工作。否则它只会占用内存。来自 在处理文件对象时,最好使用with

他关闭上面的文件。但是,在普通的学生问题中,有这样一个问题

当我试图缩短这个脚本时,当我在最后关闭文件时会出现一个错误

答:您可能做了类似的操作,indata=open(from_file).read(),这意味着当您到达脚本末尾时,不需要再执行in_file.close()操作。一旦有一行运行,Python应该已经关闭了它

那么,您如何知道何时关闭文件以及何时不关闭


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

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

来自

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


您可以在文件中的
indata=in_file.read()之后立即关闭该文件。
无论如何,您应该将
构造一起使用。您可以在不再需要读取、写入该文件时关闭该文件?对吗?不建议这样做:
indata=open(从\u文件).read()
。详情请参阅。正如这个答案所说,您应该使用
with
来打开文件,例如
with open(from_file)As indata:
。没错,但最安全、最干净的方法是使用
with
,而不是显式地调用文件的
.close
方法。
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. 
>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True