python:添加和删除行-在另一个csv中指定的操作

我正在尝试从另一个csv文件(first.csv)更新一个csv文件(original.csv),在此我需要添加或删除基于first.csv列0中指定的基于行的操作,即添加,删除。

import csv
file = 'first.csv'
with open(file) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row in csv_reader:
        if row[0] == 'add':
            with open('original.csv', 'a', newline='') as f:
                writer = csv.writer(f, quotechar="'")
                writer.writerow(row)

cat first.csv

add,apple,1,2,3
add,orange,1,2,3
delete,banana,1,2,3

cat original.csv

none,cherry,1,2,3
none,pineapple,1,2,3
none,banana,1,2,3


if column0 in first.csv is add, it will add that row in original file,
if column0 in first.csv is delete, it will delete that corresponding row (based on match of fields after `none`. delete,banana,1,2,3 == none,banana,1,2,3 both rows are same ignoring first field)

Output getting for above add method..

none,cherry,1,2,3
none,pineapple,1,2,3
none,banana,1,2,3
add,apple,1,2,3
add,orange,1,2,3

请帮助开发上述脚本,以便将与delete对应的行从原始文件中删除。

expected output:

none,cherry,1,2,3 # already exist in this file
none,pineapple,1,2,3 # already exist in this file
add,apple,1,2,3 # added from first.csv file
add,orange,1,2,3 #added from first.csv file.

请帮忙。

提前致谢。

评论