簡體   English   中英

從BIG CSV文件Python中刪除一行

[英]Delete a Line from BIG CSV file Python

我有一個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

而不是將整個列表讀入內存,而是遍歷輸入文件 ,然后將需要刪除的行以外的所有行都寫入新文件。 如果需要按索引刪除,請使用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)

您甚至可以直接在代碼中檢測到不良行,而不是使用索引。

請注意,這將寫入一個具有相同名稱但添加了.fixed的新文件。

復制完不良行以外的所有內容后,可以使用os.rename()將文件移回以替換舊文件。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM