Reputation: 11
For example, i have the following dataset :
Date,Category,Amount,Description
06-06-2022,Food,300.0,celebration
02-09-2021,transport,3300.0,operation
And am required to delete one of the entries when condition 1 (e.g. description) and condition 2 (e.g. category) are met to get the following:
Date,Category,Amount,Description
06-06-2022,Food,300.0,celebration
so far, i have no issues with the conditions statement. However, when i execute, it would produced an output for the first line with commas for each individual character and no other info.
import os
import csv
with open("filename.csv","r+") as r, open("output.csv","w") as f:
writer=csv.writer(f)
for line in r:
if condition_1 in line and condition_2 in line:
print(line) #show the line that will be deleted
else:
writer.writerow(line) #write other lines to new file
os.remove('filename.csv')
os.rename('output.csv', "filename.csv")
Any help or tips would be appreciated!
Upvotes: 1
Views: 631
Reputation: 2063
You already have a string of comma separated values in your line
variable. You don't need the csv writer.
Instead you could try opening the file in append open('output.csv', 'a')
mode and use f.write(line)
EDIT:
full code (working)
import os
with open("filename.csv", "r") as r, open("output.csv", "a") as f:
for line in r:
if 'transport' in line and '3300.0' in line:
print(line) # show the line that will be deleted
else:
f.write(line) # write other lines to new file
os.remove('filename.csv')
os.rename('output.csv', "filename.csv")
Upvotes: 0
Reputation: 822
csv
is an useful built-in standard library. With regards to learning it, you forgot to include csv.reader
. Simply pass the file as an object to csv.reader
similar to what you've done with csv.writer
.
This is a working solution that you might want:
# import os
import csv
with open("filename.csv","r+") as r, open("output.csv","w") as f:
# pass the file object to reader() to get the reader object
reader = csv.reader(r)
writer = csv.writer(f)
# Iterate over each row in the csv using reader object
for row in reader:
# row variable is a list that represents a row in csv
# print(row)
# print row as original text line
# print(', '.join(row))
if row[0] == '06-06-2022' and row[1] == 'Food':
print(f'{row} to be deleted') #show the line that will be deleted
else:
writer.writerow(row)
# os.remove('filename.csv')
# os.rename('output.csv', "filename.csv")
Try it here https://replit.com/@huydhoang/Delete-row-from-csv#main.py
Upvotes: 1