我有一个巨大的数据文件(~2 G),需要分成奇数行和偶数行,分别处理并写入两个文件,我不想将整个文件读入 RAM,所以我认为应该是生成器一个合适的选择。简而言之,我想做这样的事情:
lines = (l.strip() for l in open(inputfn))
oddlines = somefunction(getodds(lines))
evenlines = somefunction(getevens(lines))
outodds.write(oddlines)
outevens.write(evenlines)
这可能吗?显然索引不起作用:
In [75]: lines[::2]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/kaiyin/Phased/build37/chr22/segments/segment_1/<ipython-input-75-97be680d00e3> in <module>()
----> 1 lines[::2]
TypeError: 'generator' object is not subscriptable