开发者

In the Inline "open and write file" is the close() implicit?

In Python (>2.7) does the code :

open('tick.开发者_开发知识库001', 'w').write('test')

has the same result as :

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

and where to find documentation about the 'close' for this inline functionnality ?


The close() here happens when the file object is deallocated from memory, as part of its deletion logic. Because modern Pythons on other virtual machines — like Java and .NET — cannot control when an object is deallocated from memory, it is no longer considered good Python to open() like this without a close(). The recommendation today is to use a with statement, which explicitly requests a close() when the block is exited:

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

If you do not need a name f for the file, then you can omit the as clause from the statement:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜