Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of using with for opening files on Python 3?

What are the real performance advantages of using

with open(__file__, 'r') as f:

instead of using:

open(__file__,'r')

in Python 3 for both writing and reading files?

like image 639
ygbr Avatar asked May 05 '11 18:05

ygbr


People also ask

What is the advantage of using with statement in Python?

The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler.

When working with files Why is it best to open a file using with in Python?

With the “With” statement, you get better syntax and exceptions handling. “The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.” In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used.

What is the use of with statement in Python file handling?

with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Observe the following code example on how the use of with statement makes code cleaner.


3 Answers

Using with means that the file will be closed as soon as you leave the block. This is beneficial because closing a file is something that can easily be forgotten and ties up resources that you no longer need.

like image 87
unholysampler Avatar answered Oct 13 '22 19:10

unholysampler


What the with statement basically does is take advantage of two new magic keywords on an object: __enter__ and __exit__ to implement automatic cleanup (c++ destructors, .net IDisposable, etc). So what effectively happens is as follows:

file = open(__file__, 'r')
try:
  # your code here
finally: file.close()

Feel free to read a bit more about the actual implementation in pep-0343

like image 45
Bashwork Avatar answered Oct 13 '22 19:10

Bashwork


To answer your question of what performance advantage, there is none from a strict CPU/memory standpoint. Your code won't perform any better, but it will be more robust with less typing and it should be more clear and thus easier to maintain. So in a sense, the performance gain will be measured in man-hours in later maintenance, which as we all should know is the true cost of software, so it will have a great "performance advantage". ;)

like image 34
John Gaines Jr. Avatar answered Oct 13 '22 20:10

John Gaines Jr.