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()
Python has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. We can specify the mode while opening a file. In mode, we specify whether we want to read r , write w or append a to the file.
Python File read() Method The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.
Opening a file allows you to read or write to it (depending on the flag you pass as the second argument), whereas reading it actually pulls the data from a file that is typcially saved into a variable for processing or printed as output. You do not always read from a file once it is opened.
The same file can be opened more than once in the same program (or in different programs). Each instance of the open file has its own file pointer that can be manipulated independently. In python each time you call open() it creates a new file object(iterator), so you're safe.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With