![](/img/trans.png)
[英]I have a very large xml file (almost 1 gb) I need to split the xml file into 3 smaller files. All with the same headers. I would like to do in Python
[英]I need to split a very large text file
我有一个大文本文件(超过我的RAM),我需要使用它中的每一行进行进一步处理。 但是,如果我一次读出4096字节的话,我担心在两者之间将线分开。 我该怎么办?
这是你可以做的:
SIZE = 1024
with open('file.txt') as f:
old, data = '', f.read(SIZE)
while data:
# (1)
lines = data.splitlines()
if not data.endswith('\n'):
old = lines[-1]
else:
old = ''
# process stuff
data = old + f.read(SIZE)
data.splitlines(True)
,则新行字符将保留在结果列表中。 使用生成器读取文件:
def read_file(file_path):
with open(file_path, 'r') as lines:
for line in lines:
yield line
这样你一次在内存中永远不会有多行,但仍然会按顺序读取文件。
人们在音频编码批次中做这种事情,文件可能很大。 我理解它的正常方法就是有一个内存缓冲区并分两个阶段进行:将任意大小的blob读入缓冲区(4096或其他),然后从缓冲区中流出字符,对行结尾做出反应。 因为缓冲区是ram,所以逐个字符流式传输是很快的。 我不确定在Python中使用哪种数据结构或调用是最好的,我实际上只在C中完成此操作,它只是一块内存。 但同样的方法应该有效。
在linux上:
把它放到python脚本中,例如process.py :
import sys
for line in sys.stdin:
#do something with the line, for example:
output = line[:5] + line[10:15]
sys.stdout.write("{}\n".format(output))
要运行该脚本,请使用:
cat input_data | python process.py > output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.