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()
The downside of
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.