我想根据此列表过滤csv:
items = ["1", "test", "11", "9", "2003"]
之后,它应删除csv文件中与列表具有完全相同值的条目。
我的代码如下:
import csv
items = ["1", "test", "11", "9", "2003"]
Id, name, day, month, year = items
with open("database.csv", newline="") as reader:
db_readrow = csv.reader(reader, delimiter=";")
for x in db_readrow:
with open("database.csv", "w", newline="") as deleter, open("database.csv", "a", newline="") as writer:
db_deleterow = csv.writer(deleter, delimiter=";")
db_addrow = csv.writer(writer, delimiter=";")
if x[0] == "Id":
db_deleterow.writerow(["Id", "name", "day", "month", "year"])
elif Id != x[0] and name != x[1] and day != x[2] and month != x[3] and year != x[4]:
db_addrow.writerow([x[0], x[1], x[2], x[3], x[4]])
在运行此命令之前,csv如下所示:
运行它后,会发生这种情况:
有人知道如何解决此问题吗?
答案 0 :(得分:0)
让多个编写器同时运行同一文件是不太可能的。
相反,创建第二个文件并写入除要过滤掉的记录以外的所有记录。您可以删除原始文件,然后将新文件重命名为原始文件,以实现与原位写入相同的功能。