如何删除csv文件中的整行并保存对同一文件的更改?

时间:2016-09-29 11:29:04

标签: python csv

我是python的新手,并尝试修改csv文件,以便我能够根据给定的列表删除具有特定字段的特定行。 在我当前的代码中,我得到了我想删除的行,但我无法将其删除并将更改保存在同一文件中(替换)。

 import os, sys, glob
 import time ,csv
 # Open a file
 path = 'C:\\Users\\tzahi.k\\Desktop\\netzer\\'
 dirs = os.listdir( path )
 fileslst = []
 alertsCode = ("42001", "42003", "42006","51001" , "51002" ,"61001" ,"61002","71001",
          "71002","71003","71004","71005","71006","72001","72002","72003","72004",
          "82001","82002","82003","82004","82005","82006","82007","83001","84001")
 # This would print the unnesscery codes 
 for file in dirs:
    if "ALERTS" in file.upper()  :
       fileslst.append(file)
fileslst.sort()

with open(fileslst[-1], 'rb') as csvfile:
    csvReader = csv.reader(csvfile)
    for row in csvReader:
         for alert in alertsCode:
             if any(alert in row[2] for s in alertsCode) :
             print row

任何帮助?

1 个答案:

答案 0 :(得分:4)

使用 list comprehension 将所有行读入列表,并排除不需要的行。然后以模式w(写入模式)将行重写,覆盖或替换文件的内容:

with open(fileslst[-1], 'rb') as csvfile:
    csvReader = csv.reader(csvfile)
    clean_rows = [row for row in csvReader if not any(alert in row[2] for alert in alertsCode)]
    # csvfile.truncate()

with open(fileslst[-1], 'wb') as csvfile:
    csv_writer = csv.writer(csvfile)
    csv_writer.writerows(clean_rows)