I'm been stuck on this one for a while. I'm trying to open a csv, sort by severity (Critical, High, Medium, Low) then overwrite the existing file. I'd also like to ignore the first wrote or add a header row.
Original CSV
IP Address Severity Score
10.0.0.1 High 2302
172.65.0.1 Low 310
192.168.0.1 Critical 5402
127.0.0.1 Medium 1672`
Modified/Sorted CSV
IP Address Severity Score
192.168.0.1 Critical 5402
10.0.0.1 High 2302
127.0.0.1 Medium 1672
172.65.0.1 Low 310
Code
import csv
crit_sev = "Critical"
high_sev = "High"
med_sev = "Medium"
low_sev = "Low"
reader = csv.reader(open('sample.csv', 'r'))
row=0
my_list = []
for row in reader:
if row[1] == crit_sev:
my_list.append(row)
elif row[1] == high_sev:
my_list.append(row)
elif row[1] == med_sev:
my_list.append(row)
elif row[1] == low_sev:
my_list.append(row)
writer = csv.writer(open("sample.csv", 'w'))
header = ['IP Address', 'Severity', 'Score']
writer.writerow([header])
for word in my_list:
writer.writerow([word])
Any help would be appreciated.