您的位置:首页 > 编程语言 > Python开发

The best way to deal with large files in Python style

2015-04-07 15:00 495 查看
<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 = 1024with open(fpath, 'rb') as f:
while True:
block = f.read(BLOCK_SIZE)
if block:
yield block
else:
return</span>Click

here for origin.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 文件