saz*_*saz 8 python unix split python-2.7
我想将大小为50GB的大文本文件拆分成多个文件.文件中的数据是这样的 - [x = 0-9之间的任何整数]
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
...............
...............
Run Code Online (Sandbox Code Playgroud)
文件中可能有几十亿行,我想写每个文件30/40百万.我猜步骤是 -
我想知道,如何将所有这些步骤放在一个有效且更快的内存中.我在堆栈中看到了一些例子,但没有一个完全帮助我真正需要的东西.如果有人能帮助我,我真的很感激.
And*_*rey 20
此工作解决方案使用splitshell中可用的命令.由于作者已经接受了非python解决方案的可能性,请不要downvote.
首先,我创建了一个包含1000M条目(15 GB)的测试文件
awk 'BEGIN{for (i = 0; i < 1000000000; i++) {print "123.123.123.123"} }' > t.txt
Run Code Online (Sandbox Code Playgroud)
然后我用了split:
split --lines=30000000 --numeric-suffixes --suffix-length=2 t.txt t
Run Code Online (Sandbox Code Playgroud)
花了5分钟制作了一套34个名字的小文件t00- t33.33个文件各458 MB,最后一个t33是153 MB.
log*_*og0 13
from itertools import chain, islice
def chunks(iterable, n):
"chunks(ABCDE,2) => AB CD E"
iterable = iter(iterable)
while True:
# store one line in memory,
# chain it to an iterator on the rest of the chunk
yield chain([next(iterable)], islice(iterable, n-1))
l = 30*10**6
file_large = 'large_file.txt'
with open(file_large) as bigfile:
for i, lines in enumerate(chunks(bigfile, l)):
file_split = '{}.{}'.format(file_large, i)
with open(file_split, 'w') as f:
f.writelines(lines)
Run Code Online (Sandbox Code Playgroud)