Home > Mobile >  What is the correct or rather most secure way to open and close files in python?
What is the correct or rather most secure way to open and close files in python?

Time:09-17

I found many articels about this topic, but it didn't become clear to me which is the correct or rather most secure way to open and close files in python. Maybe there are more ways to use files in python, but most often I have come across these two ways:

Example 1:

with open("example.txt", "r") as f:
   # do things

Example 2:

f = open("example.txt", "r")
try:
   # do things
finally:
   f.close()

As far as I know, the only difference is that you can raise exceptions in the try..finally block. Is this correct or are there more differences? And still there is the question, which way is the correct way? I really appreciate any kind of help or suggestion, sheers!

CodePudding user response:

The most Pythonic way and a good practice is to open the file using the with statement:

with open("example.txt", "r") as f:
   # do things

And you are correct, the only difference for

f = open("example.txt", "r")
try:
   # do things
finally:
   f.close()

is that you can have a custom behavior in the finally block.

Note that using with open("example.txt", "r") as f: Python internally behaves very similar to your try-finally block as the documentation states:

IOBase is also a context manager and therefore supports the with statement. In this example, file is closed after the with statement’s suite is finished—even if an exception occurs

CodePudding user response:

Generally as from the python docs here

The with-statement is the ideal method to use here, especially as it gives many options (so you can also raise exceptions there, or check if everything went as planned or not)

The with-statement also allows custom call-backs for __exit__ and __enter__ with additional parameters to get the current state of the process.

It has some additional methods with context managers that can be more useful.

So in short, if you just use the with statement without any further functions, it basically works to make sure that the resource is closed (here being the data stream), while it also gives you the option to track the closing state, with many more options than a usual try/finally block.

I highly recommend going through the link for more information.

  • Related