Tzahi Kadosh Tzahi Kadosh - 1 year ago 74
Python Question

how to delete entire row in csv file and save changes on same file?

i'm new with python and try to modify csv file so i will able to delete specific rows with specific fields according to given list.
in my current code i get the rows which i want to delete but i can't delete it and save the changes on same file (replace).

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",
# This would print the unnesscery codes
for file in dirs:
if "ALERTS" in file.upper() :

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

any help?

Answer Source

Read all the rows into a list using a list comprehension and excluding the unwanted rows. Then rewrite the rows to the file in mode w (write mode) which overwrites or replaces the content of the file:

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download