基于两列删除csv文件中的重复项?

我有一个必须读取的CSV,并且在写入之前删除了重复的值.

重复值将基于两列(日期,价格)(AND条件语句).因此,在下面的示例中,第1行,第2行和第4行将写入CSV.第3行将符合重复条件(因为相同的日期和价格匹配第1行)并将被排除(不写入CSV).

address      floor       date         price
40 B STREET    18        3/29/2015    2200000
40 B STREET    23        1/7/2015     999000
40 B STREET    18        3/29/2015    2200000
40 B STREET    18        4/29/2015    2200000

最佳答案 你可以使用DictReader和DictWriter来完成你的任务.

import csv

def main():
"""Read csv file, delete duplicates and write it."""
    with open('test.csv', 'r',newline='') as inputfile:
        with open('testout.csv', 'w', newline='') as outputfile:
            duplicatereader = csv.DictReader(inputfile, delimiter=',')
            uniquewrite = csv.DictWriter(outputfile, fieldnames=['address', 'floor', 'date', 'price'], delimiter=',')
            uniquewrite.writeheader()
            keysread = []
            for row in duplicatereader:
               key = (row['date'], row['price'])
               if key not in keysread:
                   print(row)
                   keysread.append(key)
                   uniquewrite.writerow(row)

if __name__ == '__main__':
    main()
点赞