我正在运行一个脚本来将一些标题列恢复为 CSV 文件。它将具有标题列的原始文件作为字典,并将它们拼接回丢失标题列的文件。
问题是它非常慢。这些文件都比较大 (~50mb),有 200,000 行 x 96 列。目前,当我预览输出文件时,它看起来是正确的。大小每 10 分钟增长约 200kb。
我绝对是个编码菜鸟,所以如果能帮助我弄清楚为什么脚本这么慢,我们将不胜感激。
hapinfile = file('file_with_header_columns', 'r')
hapoutfile = file('file_missing_header_columns.csv', 'r')
o = file('filescombined.txt', 'w')
dictoutfile={}
for line in hapoutfile:
a=line.rstrip('\n').rstrip('\r').split('\t')
dictoutfile[a[0]]=a[1:]
hapinfile.close()
for line in hapinfile:
q=line.rstrip('\n').rstrip('\r').split('\t')
g=q[0:11]
for key, value in dictoutfile.items():
if g[0] == key:
g.extend(value)
o.write(str('\t'.join(g)+'\n'))
hapoutfile.close()
o.close()
请您参考如下方法:
由于嵌套的 for 循环无用地一次又一次地在 dict 中艰难跋涉,所以它花费了很长时间。试试这个:
for line in hapinfile:
q=line.rstrip('\n').rstrip('\r').split('\t')
g=q[0:11]
if g[0] in dictoutfile:
g.extend( dictoutfile[g[0]] )
o.write(str('\t'.join(g)+'\n'))
