在内联“打开和写入文件”中,close()是隐式的吗?

发布于 2021-01-29 14:58:47

在Python(> 2.7)中执行代码:

open('tick.001', 'w').write('test')

结果与:

ftest  = open('tick.001', 'w')
ftest.write('test')
ftest.close()

在哪里可以找到有关此内联功能“关闭”的文档?

关注者
0
被浏览
66
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    close()当发生此file对象从存储器释放,因为它的缺失逻辑的一部分。由于其他虚拟机(例如Java和.NET)上的现代Python无法控制何时从内存中释放对象,因此不再open()喜欢不使用python这样的对象close()。今天的建议是使用一条with语句,该语句close()在退出该块时显式请求a

    with open('myfile') as f:
        # use the file
    # when you get back out to this level of code, the file is closed
    

    如果不需要f文件名,则可以as从语句中省略该子句:

    with open('myfile'):
        # use the file
    # when you get back out to this level of code, the file is closed
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看