我有2个.csv文件,我想比较和追加。让我们说第1列文件1中有数字。我在第1列文件2中有一组类似的数字 - 但是顺序不同而且并非所有数字都存在。 我想搜索文件1列1以查看第1列文件中的数字是否匹配2.如果匹配,我想通过将列添加到匹配项中将文件2中的信息附加到文件1中数。 我也摆脱了输入文件中的任何空白行。
例如:
File 1
Number Name EmailAddress
1 Jenny jj@ymail.com
2 Josh jh@ymail.com
3 Tony ty@gmail.org
4 Jeff jf@youtube.cc
File2
Number Address
4 123 Walnut St
1 17 Yerlington Wy
7 420 St B
Output File
Number Name EmailAddress Address
4 Jeff jf@youtube.cc 123 Walnut St
1 Jenny jj@ymail.com 17 Yerlington Wy
7 NO ENTRY
这是我到目前为止的代码,它似乎做了所有事情,但附加了正确的信息。
import csv
f1 = file('inFile.csv', 'rb')
f2 = file('inFile2', 'rb')
f3 = file('outFile.csv', 'wb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)
masterlist = [row for row in c2]
for hosts_row in c1:
row = 1
found = False
for master_row in masterlist:
results_row = hosts_row
end_row = masterlist
if any(hosts_row):
if hosts_row[0] == master_row[0]:
results_row.append(end_row[row][1])
found = True
break
if not found:
results_row.append('NO ENTRY')
if any(hosts_row):
c3.writerow(results_row)
f1.close()
f2.close()
f3.close()
答案 0 :(得分:0)
首先,你的csv文件中没有分隔符,我不得不像这样重写它们(逗号分隔符):
inFile.csv:
Number,Name,EmailAddress
1,Jenny,jj@ymail.com
2,Josh,jh@ymail.com
3,Tony,ty@gmail.org
4,Jeff,jf@youtube.cc
inFile2.csv:
Number,Address
4,123 Walnut St
1,17 Yerlington Wy
7,420 St B
然后你的代码中几乎没有问题:
master_row[1]
not found
的条件位于错误的块中,因此多次附加“NO ENTRY”row
修复后:
import csv
f1 = file('inFile.csv', 'rb')
f2 = file('inFile2.csv', 'rb')
f3 = file('outFile.csv', 'wb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)
masterlist = [row for row in c2]
for hosts_row in c1:
found = False
for master_row in masterlist:
results_row = hosts_row
if hosts_row and master_row:
if hosts_row[0] == master_row[0]:
results_row.append(master_row[1])
found = True
break
if not found:
results_row.append('NO ENTRY')
if any(hosts_row):
c3.writerow(results_row)
输出文件:
Number,Name,EmailAddress,Address
1,Jenny,jj@ymail.com,17 Yerlington Wy
2,Josh,jh@ymail.com,NO ENTRY
3,Tony,ty@gmail.org,NO ENTRY
4,Jeff,jf@youtube.cc,123 Walnut St
HTH
答案 1 :(得分:0)
另一种看法(这个产生了你呈现的输出,但我想Tomás的输出就是你所描述的):
import csv
def read_file(path):
with open(path) as fh:
data = csv.reader(fh)
return [row for row in data if row]
def match(l1, l2):
result = []
for i in l2:
match = False
for j in l1:
if i[0] == j[0]:
row = j + i[1:]
match = True
break
if not match:
row = [i[0], "NO ENTRY"]
result.append(row)
return result
if __name__ == '__main__':
l1 = read_file("inFile.csv")
l2 = read_file("inFile2")
result = match(l1, l2)
of = open('outFile.csv', 'w')
writer = csv.writer(of)
writer.writerows(result)
of.close()
几点说明:
您应该使用open
代替file
;在文件模式下,b
用于二进制文件(通过在文本模式下打开,可以进行行终止的转换)。还有更多,但已经解决了。