我有一个python代码,它将获取sample.csv文件的第一列并将其复制到temp1.csv文件。现在我想将此csv文件与任何常见行的另一个serialNumber.txt文件进行比较。如果找到任何常见行,则应写入结果文件。我的temp1.csv正在正确创建,但问题是正在创建的结果文件是空的。
script.py
import csv
f = open("sample.csv", "r")
reader = csv.reader(f)
data = open("temp1.csv", "wb")
w = csv.writer(data)
for row in reader:
my_row = []
my_row.append(row[0])
w.writerow(my_row)
data.close()
with open('temp1.csv', 'r') as file1:
with open('serialNumber.txt', 'r') as file2:
same = set(file1).intersection(file2)
print same
with open('result.csv', 'w') as file_out:
for line in same:
file_out.write(line)
print line
sample.csv
M11435TDS144,STB#1,Router#1
M11543TH4292,STB#2,Router#1
M11509TD9937,STB#3,Router#1
M11543TH4258,STB#4,Router#1
serialNumber.txt
G1A114042400571
M11543TH4258
M11251TH1230
M11435TDS144
M11543TH4292
M11509TD9937
答案 0 :(得分:0)
with open('temp1.csv', 'r') as file1:
list1 = file1.readlines()
set1 = set(list1)
with open('temp2.csv', 'r') as file2:
list2 = file2.readlines()
set2 = set(list2)
现在您可以将内容处理为集
我想请注意,您的原始代码不会在每行后插入换行符,因此我不确定它们是否存在。如果不是你需要添加那些,否则你会有一团糟
答案 1 :(得分:0)
你可能想要这个
same = set(list(file1)).intersection(list(file2))