To read contents of a file:
data = open(filename, \"r\").read()
The open file immediately stops being referenced anywhere, so the file obje
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()
It is true that it will close eventually, but eventually might not be soon enough. Especially if you're using this inside a loop, the system might run out of file handles before the GC gets to the file objects.
The code works exactly as you say it does, but it's bad style nevertheless. Your code relies on assumptions which may be true now, but won't always be true. It's not impossible that your code will be run in a situation where the file being opened and not close does matter. Is it really worth that risk just to save 1 or 2 lines of code? I don't think so.
looks fine to me.. I read files like that often.
No, it's perfectly reasonable Python style IMO, as per your reasoning.
Update: There are a lot of comments here about whether file objects get tidied up straight away or not. Rather than speculate, I did some digging. Here's what I see:
The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement reference counts. Py_DECREF calls the object's deallocator function when the refcount falls to 0
Looking in Python's fileobject.c:
The function table for file objects points to function file_dealloc
. This function
calls close_the_file
, which in turn closes the file.
Even though it works as expected, I think it fails in two counts:
import this
in the Python prompt to retrieve it) "explicit is better than implicit" and, by failing to explicitly close the file, you could confuse someone who, down the road, will be left with your code for maintenance.It really helps being explicit! Python encourages explicit style.
Other than that, for a throwaway script, your style makes sense.
Maybe you will benefit from this answer.