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

后端 未结 1 2028
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 11:57

In Python (>2.7) does the code :

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

has the same result as :

ftest  = open(\'tick.         


        
相关标签:
1条回答
  • 2020-12-20 12:33

    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 讨论(0)
提交回复
热议问题