ygbr
ygbr

Reputation: 750

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?

Upvotes: 10

Views: 5512

Answers (4)

Bashwork
Bashwork

Reputation: 1619

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

Upvotes: 9

John Gaines Jr.
John Gaines Jr.

Reputation: 11544

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". ;)

Upvotes: 2

Cédric Julien
Cédric Julien

Reputation: 80811

with the classical syntax you have to take care of closing the file, thus even if an exception occured during file treatment.

IMHO On the other side, with the with statement, you are able to write smaller code, easier to read, python is taking care of closing the file after you leave the with block.

Upvotes: 1

unholysampler
unholysampler

Reputation: 17341

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.

Upvotes: 12

Related Questions