About open file for Read
d at davea.name
Mon Dec 10 18:14:18 CET 2012
On 12/10/2012 11:36 AM, moonhkt wrote:
> Hi All
> I am new in Python. When using open and then for line in f .
> Does it read all the data into f object ? or read line by line ?
> f=open(file, 'r')
> for line in f:
> if userstring in line:
> print "file: " + os.path.join(root,file)
open() does not read the whole file into any object. There is buffering
that goes on in the C libraries that open() calls, but that should be
transparent to you for regular files.
When you ask for a line, it'll read enough to fulfill that request, and
maybe some extra that'll get held somewhere in the C runtime library.
You should look into the 'with' statement, to avoid that f.close().
That way the file will be closed, regardless of whether you get an
exception or not.
with open(file,. "r") as f:
for line in f:
BTW, since you're in version 2.x, you should avoid hiding the builtin
file object. Call it something like file_name, or infile_name.
More information about the Python-list