With the requirement, if you read the whole file right away?

I have been using this since 12 years:

content=open(foo).read()

New colleagues from the university say: you must use the instructions with.

with open(foo) as fd:
    content=fd.read()

I see no good reason why I should introduce more than necessary.

The only advantage that the instruction gives is with: it fdcloses as soon as the block remains on the left. Without an operator, it with fdcloses if the garbage collector begins to do its job.

Please tell me why should I use the instructions withif I read the whole file right away?

Update . I know how the with statement works, I know that it is useful (for example, writing to a file).

+4
5

, , , . , ( ), with , __del__. , with , - :

. Python ( , 5- PyPy, , - !). , . ( !) .

script, , - . .

0

, . with . . :

import threading
lock = threading.Lock()
with lock:
    # Critical section
    statements
    # End critical section

with , .

, ( ), , with, .

+5

: , , . .

, :

content = open('foo.txt').read()
os.unlink('foo.txt')

Linux, Windows, , Windows ( - , ).

with open('foo.txt') as fp:
    content= fp.read()
os.unlink('foo.txt')

() .

+1

GC.

, , with . , , , - with.

0

with , , , .

-3
source

All Articles