从大型CSV文件Python中删除一行

从大型CSV文件Python中删除一行,python,python-3.x,file,Python,Python 3.x,File,我有一个11GB的CSV文件,其中有一些损坏的行我必须删除,我已经从ETL接口识别出损坏的行号 然而,当我想在主文件上运行时,我的程序运行的是小数据集,我得到的是MemoryError。在我使用的代码下面,你有什么建议让它工作吗 row_to_delete = 101068 filename = "EKBE_0_20180907_065907 - Copy.csv" with open(filename, 'r', encoding='utf8' ,errors='ignore') as fil

我有一个11GB的CSV文件,其中有一些损坏的行我必须删除,我已经从ETL接口识别出损坏的行号

然而,当我想在主文件上运行时,我的程序运行的是小数据集,我得到的是MemoryError。在我使用的代码下面,你有什么建议让它工作吗

row_to_delete = 101068
filename = "EKBE_0_20180907_065907 - Copy.csv"
with open(filename, 'r', encoding='utf8' ,errors='ignore') as file:
    data = file.readlines()
    print(data[row_to_delete -1 ])
    data [row_to_delete -1] = ''
with open(filename, 'wb',encoding="utf8",errors='ignore') as file:
    file.writelines( data )
错误:

Traceback (most recent call last):
  File "/.PyCharmCE2018.2/config/scratches/scratch_7.py", line 7, in <module>
    data = file.readlines()
MemoryError
回溯(最近一次呼叫最后一次):
文件“/.PyCharmCE2018.2/config/scratches/scratch_7.py”,第7行,在
data=file.readlines()
记忆者

不要将整个列表读取到内存中,而是循环输入文件,并将除需要删除的行之外的所有行写入新文件。如果需要按索引删除,请使用
enumerate()
保留计数器:

row_to_delete = 101068
filename = "EKBE_0_20180907_065907 - Copy.csv"
with open(filename, 'r', encoding='utf8', errors='ignore') as inputfile,\
     open(filename + '.fixed', 'wb', encoding="utf8") as outputfile:
    for index, line in enumerate(inputfile):
        if index == row_to_delete:
            continue  # don't write the line that matches
        outputfile.writeline(line)
您甚至可以通过这种方式直接在代码中检测错误行,而不用使用索引

请注意,这会写入一个新文件,该文件的名称相同,但添加了
。已修复

复制完除坏行以外的所有行后,如果愿意,可以将该文件移回以替换旧文件:

os.rename(filename + '.fixed', filename)