我使用Python在一个大csv文件(120万行,250MB)中查找一些模式,如果找到这样的模式,则对每行执行一些修改。 我的方法是这样的:
dfile=open(csvfile,'r')
lines=dfile.readlines()
dfile.close()
for i in range(0, len(lines)):
lines[i]=f(lines[i])
# f(.) is a function that modifies line string if a pattern is found
# then I have a code to write the processed data in another csv file.
问题是在某些迭代之后,代码停止运行,返回内存错误。我的系统有32GB内存。 如何提高内存性能? 我尝试使用以下方法逐行读取数据:
import cache
j=1
while True:
line=cache.getline(csvfile,j)
if line='':
break
outp=open(newfile,'w')
outp.write(f(line))
outp.close()
j+=1
这种方法也失败了:
encoding error reading location 0X9b?!
有什么解决办法吗?你知道吗
如果你对我的csv文件中的函数和模式感兴趣,瞧。 这是我的csv文件的一个小例子。你知道吗
Description Effectivity AvailableLengths Vendors
Screw 2" length 3" "machine1, machine2" 25mm "vend1, ven2"
pin 3" machine1 2-3/4" vend3
pin 25mm "machine2, machine4" 34mm "vend5,Vend6"
Filler 2" red machine5 "4-1/2", 3"" vend7
"descr1, descr2" "machin1,machin2,machine3" 50 "vend1,vend4"
csv文件中的字段用逗号分隔,因此第一行如下所示:
Screw 2" length 3","machine1, machine2",25mm,"vend1, ven2"
由于多值字段和对维度使用引号,csv读取器无法读取此文件。如果逗号位于属于同一字段的两个数据之间,我的函数(上面代码中的函数f)将逗号替换为分号;如果引号是维度,则将逗号替换为“INCH”。你知道吗
f(firstline)=Screw 2INCH length 3INCH,machine1;machine2,25mm,vend1;ven2
尝试使用以下方法来编码错误:
就性能而言,函数f()的问题可能在于它的复杂性/内存消耗很高。你知道吗
你能把函数f()粘贴在这里吗?如果你想找到一个模式,你也可以考虑使用regex。你知道吗
相关问题 更多 >
编程相关推荐