File open: Is this bad Python style?
coding-style, file, file-io, python
Solution
Just for the record: This is only slightly longer, and closes the file immediately:
from __future__ import with_statement
with open(filename, "r") as f:
data = f.read()
Problem
To read contents of a file: ``` data = open(filename, "r").read() ``` The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing. EDIT: This has actually bitten me in a project I wrote - it prompted me to ask this question. File objects are cleaned up only when you run out of memory, not when you run out of file handles. So if you do this too often, you could end up running out of file descriptors and causing your IO attempts at opening files to throw exceptions.