<span style="font-family:Arial Black;font-size:12px;color:#000099;">with open(...) as f: for line in f: <do something with line></span>
The with
statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f
treats the file object f
as an iterable, which automatically uses buffered IO and memory management so you don't have to worry about large files.
Click here for origin.
Another alternative: by making use of yield.
<span style="font-family:Arial Black;font-size:12px;">def read_file(fpath):
BLOCK_SIZE = 1024
with open(fpath, 'rb') as f:
while True:
block = f.read(BLOCK_SIZE)
if block:
yield block
else:
return</span>
Click
here for origin.