Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is open().read() safe?

Tags:

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() 
like image 886
Brigand Avatar asked Mar 22 '12 21:03

Brigand


People also ask

What does open () read () do in Python?

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.

What is read () in Python?

Python File read() Method The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.

What is the difference between open and read?

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.

Can you open a file twice in Python?

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.


2 Answers

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.

like image 58
Greg Hewgill Avatar answered Nov 05 '22 23:11

Greg Hewgill


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.

like image 36
hc_ Avatar answered Nov 05 '22 21:11

hc_