Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

file

io

Frequently when someone posts their code, people will add as an aside that "you should use with open('filename') as f syntax now." I agree that most of the old-fashioned f = open() statements don't have an accompanying .close(), and I have even answered questions where this reliance on "implicit close" was the entire cause of their programming problem.

However, in some cases nesting your code inside the with block seems to create other inconveniences in writing the code. For example I sometimes like to use a flag at the beginning to say writefile = True. This lets me only open and close the file if it is going to be used, while keeping the same processing thread. At various places in the code I can either print to screen or write to a file. (I realize I would open stdout or the file at the beginning and use that approach instead.)

My question is: besides not having to explicitly close the file, are there other reasons to use the with syntax for handling files, especially output files? ("More pythonic" by itself is not a reason.) If this is a duplicate, I would be glad to have this pointed out, but I couldn't find it myself.

like image 999
beroe Avatar asked Oct 31 '13 16:10

beroe


People also ask

Why should I use with Open in Python?

When you use with statement with open function, you do not need to close the file at the end, because with would automatically close it for you. This PEP adds a new statement " with " to the Python language to make it possible to factor out standard uses of try/finally statements.

What is the significance of using with statement for opening a file?

In with open() the closing of the file is handled by the context manager. Using with open() context statement makes the code more tidy as we can easily separate between code block by difference in indents.

What does with open () do in Python?

What Does Open() Do in Python? To work with files in Python, you have to open the file first. So, the open() function does what the name implies – it opens a file for you so you can work with the file.

What is the difference between with open and open in Python?

Within the block of code opened by “with”, our file is open, and can be read from freely. However, once Python exits from the “with” block, the file is automatically closed.


1 Answers

There's no other advantage of with: ensuring cleanup is the only thing it's for.

You need a scoped block anyway in order to close the file in the event 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, the thing you describe as a disadvantage of with is really a disadvantage of correct code (in the case where cleanup is required), no matter how you write it.

like image 122
Steve Jessop Avatar answered Oct 22 '22 10:10

Steve Jessop