简体   繁体   中英

Delete data in csv file using python?

I have two csv files with a single column of data. How can I remove data in the second csv file in-place by comparing it with the data in the first csv file? For example:

 import csv
 reader1 = csv.reader(open("file1.csv", "rb")) 
 reader = csv.reader(open("file2.csv", "rb"))f
 for line in reader:
     if line in reader1:
         print line

文件2

if both files are just single columns, then you could use set to remove the differences. However, this presumes that the entries in each file do not need to be duplicated and their order doesn't really matter.

#since each file is a column, unroll each file into a single list:
dat1 = [x[0] for x in reader1]
dat2 = [y[0] for y in reader]

#take the set difference
dat1_without_dat2 = set(dat1).difference(dat2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM