python出来后关闭文件吗?

时间:2017-12-20 19:41:20

标签: python python-3.6

我厌倦了两个代码示例,一个是close,另一个是close,strace说两个代码都调用了.close()

可以安全地理解python3.6自动关闭:

例1: 文件中的行是:

f = open('./myConfig.cfg')
jsonda = json.loads(f.read())

相应的strace o / p是

open("./myConfig.cfg", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=693, ...}) = 0
ioctl(3, TCGETS, 0x7ffe829a80a0)        = -1 ENOTTY (Inappropriate ioctl for device)
lseek(3, 0, SEEK_CUR)                   = 0
ioctl(3, TCGETS, 0x7ffe829a8040)        = -1 ENOTTY (Inappropriate ioctl for device)
lseek(3, 0, SEEK_CUR)                   = 0
lseek(3, 0, SEEK_CUR)                   = 0
fstat(3, {st_mode=S_IFREG|0644, st_size=693, ...}) = 0
read(3, "{\n  \"osns\" : [\n    {\n      \"fabr"..., 694) = 693
read(3, "", 1)                          = 0
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f57b2bc1390}, {0x442160, [], SA_RESTORER, 0x7f57b2bc1390}, 8) = 0
close(3)                                = 0
sigaltstack(NULL, {ss_sp=0x1f2b0b0, ss_flags=0, ss_size=8192}) = 0
sigaltstack({ss_sp=NULL, ss_flags=SS_DISABLE, ss_size=0}, NULL) = 0
exit_group(0)                           = ?
+++ exited with 0 +++

同样在第二个文件中:

f = open('./myConfig.cfg')
jsonda = json.loads(f.read())
f.close()

相应的strace o / p是

open("./myConfig.cfg", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=693, ...}) = 0
ioctl(3, TCGETS, 0x7fff2e3f27c0)        = -1 ENOTTY (Inappropriate ioctl for device)
lseek(3, 0, SEEK_CUR)                   = 0
ioctl(3, TCGETS, 0x7fff2e3f2760)        = -1 ENOTTY (Inappropriate ioctl for device)
lseek(3, 0, SEEK_CUR)                   = 0
lseek(3, 0, SEEK_CUR)                   = 0
fstat(3, {st_mode=S_IFREG|0644, st_size=693, ...}) = 0
read(3, "{\n  \"osns\" : [\n    {\n      \"fabr"..., 694) = 693
read(3, "", 1)                          = 0
close(3)                                = 0
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f4f52f6d390}, {0x442160, [], SA_RESTORER, 0x7f4f52f6d390}, 8) = 0
sigaltstack(NULL, {ss_sp=0x15130b0, ss_flags=0, ss_size=8192}) = 0
sigaltstack({ss_sp=NULL, ss_flags=SS_DISABLE, ss_size=0}, NULL) = 0
exit_group(0)                           = ?
+++ exited with 0 +++

1 个答案:

答案 0 :(得分:1)

请参阅文档的这一部分Reading and writing files,它完全回答了您的问题,因此“阅读文档”。我将从那里提供一个引用:

  

如果您未使用with关键字,则应致电f.close()   关闭文件并立即释放所使用的任何系统资源   它。如果您没有显式关闭文件, Python的垃圾收集器   最终会破坏对象并关闭打开的文件,   但文件可能会保持打开一段时间。另一个风险是不同的   Python实现将在不同时间进行清理。

同一部分的另一部分提倡使用with块,因为在这种情况下,即使在某个时刻引发异常,我也保证正确释放资源(我想除了SystemError) :

  

在处理文件时,最好使用with关键字   对象。优点是文件在其之后正确关闭   即使在某个时刻出现异常,套件也会完成。运用   with也比编写等效的try-finally块短得多。

最终回答你的问题 - 是的,可以安全地假设Python自动关闭,但隐含地依赖它是不安全的。