open read and close a file in 1 line of code
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping
--
Chapters
00:00 Open Read And Close A File In 1 Line Of Code
00:20 Accepted Answer Score 254
00:48 Answer 2 Score 190
01:09 Answer 3 Score 27
01:46 Answer 4 Score 24
02:17 Answer 5 Score 12
02:44 Thank you
--
Full question
https://stackoverflow.com/questions/8011...
--
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'
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:
In Python implementations different from CPython, the file often isn't immediately closed, but rather at a later time, beyond your control.
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.