【发布时间】:2017-09-15 18:08:34
【问题描述】:
我有以下代码尝试处理包含多个 xml 元素的大文件。
from shutil import copyfile
files_with_companies_mentions=[]
# code that reads the file line by line
def read_the_file(file_to_read):
list_of_files_to_keep=[]
f = open('huge_file.nml','r')
lines=f.readlines()
print("2. I GET HERE ")
len_lines = len(lines)
for i in range(0,len(lines)):
j=i
if '<?xml version="1.0"' in lines[i]:
next_line = lines[i+1]
write_f = open('temp_files/myfile_'+str(i)+'.nml', 'w')
write_f.write(lines[i])
while '</doc>' not in next_line:
write_f.write(next_line)
j=j+1
next_line = lines[j]
write_f.write(next_line)
write_f.close()
list_of_files_to_keep.append(write_f.name)
return list_of_files_to_keep
该文件超过 700 MB,包含超过 2000 万行。有没有更好的处理方法?
如您所见,我需要使用诸如i 之类的指标变量来引用上一行和下一行。
我面临的问题是它非常慢。每个文件都需要 1 个多小时,而我有多个。
【问题讨论】:
-
您面临的问题是什么?磁盘空间?
-
速度很慢。我编辑了我的原始帖子。
-
并行处理如何同时处理这些文件中的几个?
-
您可以执行“for line in f:”,然后根据需要逐行逐行执行,而无需先将它们全部读入内存。您需要重新设计查找 的逻辑,方法是设置一个布尔标志来指示您是否正在查找它。
-
你能给我一个代码的答案,以便我可以尝试吗?
标签: python