Close file using operator in Python

I have a question about closing a file in a python withoperator

   import os

    with os.popen('ls') as f:
        print f.read()
        raise IOError
        print f
    print f

As you can see in the code snippet above, I open the file using the operator with, I know that the file will be closed automatically after exiting the block with, but if some kind of error occurs inside the block, does it happen with the file f, will it be closed?

+4
source share
4 answers

Yes. From python docs:

- , , with. . with ( The with statement), .

, try..except..finally . , : , .

+4

, . PEP 343 with:

- object __exit__(), .

: subprocess.Popen ( subprocess.call ) os.popen ( Python 2.6).

+3

, , , :

with open('somefile.txt') as f:
    a = f.read()
    print(f.closed) # Will print False
    raise IOError

print(f.closed) # Will print True
+2

,

with.

0

Source: https://habr.com/ru/post/1682635/


All Articles