このような巨大なファイルを一度に 1 行ずつ解析するか、ファイルを小さなチャンクに分割するには、必ず遅延ジェネレーターを使用する必要があります。
1 つの可能性:
def lazy_reader(path):
"""reads a file one line at a time."""
try:
file = open(path, 'r')
while True:
line = file.readline()
if not line: break
yield line # "outputs" the line from the generator
except IOError:
sys.stderr.write("error while opening file at %s\n" % path)
sys.exit(2)
finally:
file.close()
そして、このようにジェネレーターを消費できます
for line in lazy_reader("path/to/your/file"):
do_something_with(line)
EDIT:ジェネレーターをきちんとした「パイプライン」の方法で組み合わせることもできます:
def parse(generator):
for line in generator: yield line.strip('\n').split('|')
for data in parse( lazy_reader("path/to/your/file") ):
do_something_with_splitted_array(data)