Open reading and close the file in 1 line of code

Now I use:

pageHeadSectionFile = open('pagehead.section.htm','r') output = pageHeadSectionFile.read() pageHeadSectionFile.close() 

But to make the code look better, I can do:

 output = open('pagehead.section.htm','r').read() 

Using the syntax above, how to close a file to free up system resources?

+65
python readfile
Nov 04 2018-11-11T00:
source share
9 answers

You really don't need to close it - Python will do this automatically either during garbage collection or when you exit the program. But, as @delnan noted, it’s better to practice explicitly closing it for various reasons.

So what can you do to make it short, simple, and explicit:

 with open('pagehead.section.htm','r') as f: output = f.read() 

Now these are just two lines and quite readable, I think.

+109
Nov 04 '11 at 15:37
source share

Using CPython, your file will be closed immediately after the line is executed, since the file file immediately collects garbage. There are two drawbacks:

  • In Python implementations other than CPython, the file often does not close immediately, but rather later, beyond your control.

  • In Python 3.2 or later, this will call ResourceWarning if enabled.

It is better to invest one additional line:

 with open('pagehead.section.htm','r') as f: output = f.read() 

This ensures that the file is properly closed under any circumstances.

+16
Nov 04 '11 at 15:38
source share

What you can do is use the with statement:

 >>> with open('pagehead.section.htm', 'r') as fin: ... output = fin.read() 

The with statement will take care of calling the __exit__ function of this object, even if something happened in your code; it is close to try... finally syntax. For the object returned by open , __exit__ corresponds to closing the file.

This operator was introduced with Python 2.6.

+9
Nov 04 '11 at 15:39
source share

The standard Python Pathlib library module does what you are looking for:

 jsk@dev1:~$ python3 Python 3.5.2 (default, Sep 10 2016, 08:21:44) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from pathlib import Path >>> (Path("/etc") / "hostname").read_text() 'dev1.example\n' 
+6
Nov 11 '16 at 16:11
source share

use ilio : (inline io):

only one function call instead of the file open (), read (), close ().

 from ilio import read content = read('filename') 
+5
Aug 21 '15 at 13:42 on
source share
 with open('pagehead.section.htm')as f:contents=f.read() 
+2
Dec 23 '16 at
source share

I often do something like this when I need to get a few lines surrounding something that I found in the log file:

 $ grep -n "xlrd" requirements.txt | awk -F ":" '{print $1}' 54 $ python -c "with open('requirements.txt') as file: print ''.join(file.readlines()[52:55])" wsgiref==0.1.2 xlrd==0.9.2 xlwt==0.7.5 
0
Feb 06 '15 at 18:19
source share

Using more_itertools.with_iter , you can open, read, close, and assign the equivalent of output in one line (excluding import):

 import more_itertools as mit output = "".join(line for line in mit.with_iter(open("pagehead.section.htm", "r"))) 

Although perhaps I would be looking for a different approach than setting the contents of the file to a variable, i.e. lazy iteration - this can be done using the traditional with block or in the example above by removing join() and iteration output .

0
Aug 29 '17 at 1:24 on
source share

No need to import anything.

Just use regular syntax and it will open the file for reading and then close it.

 with open("/etc/hostname","r") as f: print f.read() 

or

 with open("/etc/hosts","r") as f: x = f.read().splitlines() 

which gives you an x ​​array containing strings that can be printed like this:

 for i in range(len(x)): print x[i] 

These single line lines are very obvious.

0
Sep 10 '17 at 5:21 on
source share



All Articles