The Python Oracle

open read and close a file in 1 line of code

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 Question
00:31 Accepted answer (Score 249)
01:03 Answer 2 (Score 158)
01:32 Answer 3 (Score 27)
02:13 Answer 4 (Score 22)
02:54 Thank you

--

Full question
https://stackoverflow.com/questions/8011...

Answer 1 links:
[Pathlib]: https://docs.python.org/3/library/pathli...
[pathlib]: https://pypi.python.org/pypi/pathlib
[pathlib2]: https://pypi.python.org/pypi/pathlib2

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #readfile

#avk47



ACCEPTED ANSWER

Score 254


You don't really have to close it - Python will do it automatically either during garbage collection or at program exit. But as @delnan noted, it's better practice to explicitly close it for various reasons.

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

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

Now it's just two lines and pretty readable, I think.




ANSWER 2

Score 190


Python Standard Library Pathlib module does what you looking for:

Path('pagehead.section.htm').read_text()

Don't forget to import Path:

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'

On Python 27 install backported pathlib or pathlib2




ANSWER 3

Score 27


Using CPython, your file will be closed immediately after the line is executed, because the file object is immediately garbage collected. There are two drawbacks, though:

  1. In Python implementations different from CPython, the file often isn't immediately closed, but rather at a later time, beyond your control.

  2. In Python 3.2 or above, this will throw a ResourceWarning, if enabled.

Better to invest one additional line:

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

This will ensure that the file is correctly closed under all circumstances.




ANSWER 4

Score 12


What you can do is to use the with statement, and write the two steps on one line:

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

The with statement will take care to call __exit__ function of the given object even if something bad happened in your code; it's close to the try... finally syntax. For object returned by open, __exit__ corresponds to file closure.

This statement has been introduced with Python 2.6.