Reputation: 117
I know that it is a lot better to use
with open(...)...
but I was wondering if there is ever a case where using
open(...)
has any advantage in any situation.
Upvotes: 0
Views: 1209
Reputation: 67
within the block of code opened by with
, file is open, and can be read from freely. However, when Python exits from the with
block, the file is automatically closed.
so if you might do a lot of stuff with the same file in your program (if you have some user interface program with some calculations, for example) you might want to keep file open instead of closing and reopening it again and again.
Upvotes: 0
Reputation: 158
file = open(...)
requires you to close that file again with file.close()
. with open(...) does this for you. Else there's no difference.
Upvotes: -1
Reputation: 2489
Yes. with open(...)
manages the file descriptor for you so once the with block is done python automatically closes the file descriptor for you. However in some scenarios it might be more performant / necessary to keep the file descriptor. A simple example would be a function that opens a file and writes a header line and passes the file descriptor back:
def open_and_write_header(filename):
f = open(filename, 'w')
f.write('This is my header')
return f
file_desc = open_and_write_header('testfile.txt')
file_desc.write('This is my tail')
file_desc.close()
Whereas if we use the with
syntax:
def open_and_write_header(filename):
with open(filename, 'w') as f:
f.write('This is my header')
return f
file_desc = open_and_write_header('testfile.txt')
file_desc.write('This is my tail')
file_desc.close()
we get:
Traceback (most recent call last):
File "stack.py", line 7, in <module>
file_desc.write('This is my tail')
ValueError: I/O operation on closed file.
Upvotes: 5