Why is `open ()` better for opening files in Python?

Often, when someone submits their code, people will add to the side that "you must use the syntax with open('filename') as f." I agree that most old-fashioned statements f = open()do not have an accompanying one .close(), and I even answered questions where this dependence on “implicit closure” was the whole reason for their programming problem.

However, in some cases, embedded code inside a block withcreates other inconveniences when writing code. For example, I sometimes like to use the flag at the beginning to say writefile = True. This allows me to open and close the file if it will be used, while maintaining the same processing flow. In different places in the code, I can either print on the screen or write to a file. (I understand that I would open stdouteither the file at the beginning and use this approach.)

My question: Also, there is no need to explicitly close the file, are there any other reasons to use the syntax withto process the files , especially the output files? ("More pythons" is not a cause in itself.) If it is a duplicate, I would be glad if it were indicated, but I could not find it myself.

+4
source share
4 answers

There is no other advantage with: providing cleaning is the only thing you need for.

In any case, you need a cloud block to close the file in case of an exception:

writefile = random.choice([True, False])
f = open(filename) if writefile else None
try:
    # some code or other
finally:
    if writefile:
        f.close()

So, what you describe as a flaw withis really a flaw in the correct code (in the case where a cleanup is required), no matter how you write it.

+6
source

We want to ensure that some cleanup / finalization occurs. This is the use with.

Yes, most often we would like to close the file, but you could come up with other examples.

PEP 343 has an example without a file:

, , , :

@contextmanager
def locked(lock):
    lock.acquire()
    try:
        yield
    finally:
        lock.release()

:

with locked(myLock):
    # Code here executes with myLock held.  The lock is
    # guaranteed to be released when the block is left (even
    # if via return or by an uncaught exception).
+3

, ,

, ContextManager , , - .

f = open(filename, 'w')
try:
    pass
finally:
    f.close()
+1

, , writefile = True. , , . , . ( , stdout .)

This section describes code with many duplicate if statements.

In addition, there is no need to explicitly close the file, are there other reasons to use the syntax for processing files, especially the output files?

This eliminates the need to write your own blocks finally, and it structures your code so that you avoid duplicate if statements, and this allows readers to easily find the place where the file object (or rather, the variable containing the file object).

So, instead of a mess of flags, you can do:

with (open('file') if condition else io.BufferedWriter(sys.stdout)) as f:
     pass
+1
source

All Articles