Reputation: 86260
I write a lot of Python code where I just want to read a file to a variable. I know the two recommended ways are these -
with open('file') as f:
data = f.read()
# or
fo = open('file')
data = f.read()
fo.close()
My questions, is what are the downsides of this?
data = open('file').read()
Upvotes: 22
Views: 12889
Reputation: 22007
According to an answer in a similiar question (this time, concerning writes), the main downside is that you have no control over when that file will be closed. The problem is more significant for writes (since you're altering the file), but it still means you have an unclosed file handle until the object is reclaimed by the garbage collector.
Many generational gcs will clear these kinds of objects (created in a scope, with no remaining references to it in the end of the scope) right away, but it can't be guaranteed. So, it's better to stick to explicit file closing to be sure.
Upvotes: 2
Reputation: 994121
The downside of
data = open('file').read()
is that depending on your Python implementation, the cleanup of the open file object may or may not happen right away. This means that the file will stay open, consuming a file handle. This probably isn't a problem for a single file, but in a loop it could certainly be trouble.
In specific terms, CPython (the usual Python implementation) uses reference counted objects so the file close almost certainly will happen right away. However, this is not necessarily true for other implementations such as IronPython or Jython.
Upvotes: 25
Reputation: 2628
The downside is that after both, the first and the second block you can be sure that your file is closed. (In the first instance even in case an exception was raised.)
The short form doesn't give you any such guarantee.
Upvotes: 6