I have a CSV file which contains multiple Row and columns. Based on the if condition I need to filter the date and I want to write that filtered data to new CSV file.
So I have written this below code for the same however I'm getting only one row but we have many rows in the filtered data.
Could you please help me to fix the issue.
Code:
import CSV
with open('testfilename.csv','r') ad file
csv_reader = csv.reader (csv_file)
rows = [ row for row in csv_reader]
filtered_rows1 = []
filtered_rows2 = []
for row in rows:
if(row[3] == "CRITICAL"):
filtered_rows1.append(row)
with open('Critical.csv','w', newline='') as csv_file
csv_writer = CSV.writer(csv_file)
for row in filtered_rows1:
csv_writerow(row)
elif(row[3] == "URGENT"):
filtered_rows2.append(row)
with open('Urgent.csv','w', newline='') as csv_file
csv_writer = CSV.writer(csv_file)
for row in filtered_rows2:
csv_writerow(row)
CodePudding user response:
The code needs a little refactoring.
import csv
with open('testfilename.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
# Store the rows in a list
rows = [row for row in csv_reader]
# Create a new list to store the filtered rows
filtered_rows = []
# Iterate over the rows in the list
for row in rows:
# Check if the row meets the desired condition
if row[3] == 'CRITICAL':
# If the row meets the condition, append it to the filtered rows list
filtered_rows.append(row)
with open('testfilenameV1.csv', 'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file)
for row in filtered_rows:
csv_writer.writerow(row)
CodePudding user response:
Your issue is most likely that you are opening the file testfilenameV1.csv
in write mode every time you add a row. This means that the file will be truncated each time (existing contents will be deleted). You should either open the file in append mode (pass 'a'
instead of 'w'
as the second argument to open
), or you should open the file outside of your for row in myFile
loop so that it's only truncated at the beginning of the script, rather than during each iteration when your if condition passes.
I'm also not exactly sure whether it's a problem that you're creating a new CSV writer each time, but I would suggest moving the myFile2 = csv.writer(file2)
line outside of your for loop as well.
Overall this could look something like this:
import csv
with open('testfilename.csv', 'r') as file:
myFile = csv.reader(file)
with open('testfilenameV1.csv', 'w', newline='') as file2:
myFile2 = csv.writer(file2)
for row in myFile:
if row[3] == "CRITICAL":
myFile2.writerow(row)