Excel文件需要先另存为CSV文件
one.csv:
列0, 列1, 列2, 列3
1, a, ww.ok;ww.ant;, anything
2, e, ww.kdi;, ihy
3, se, ww.sdd, sld
4, sd, ww.akd,
two.csv:
列0, 列1, 列2, 列3
1, sd, ww.ok;, 1245
2, 2e3, ww.kdi;, 432
3, de, ww.sdd;, 232
目标:判断one.csv列2中是否包含two.csv文件列2的域名,如果包含,则将two.csv列3的数据追加到one.csv对应行的末尾,最终结果效果如下(如果是Excel文件,先存为csv文件再操作):
result.csv:
列0, 列1, 列2, 列3, 列4
1, a, ww.ok;ww.ant;, anything, 1245
2, e, ww.kdi;, ihy, 432
3, se, ww.sdd, sld, 232
4, sd, ww.akd, ,
完整源码
import csv
def csv2list(filepath):#读取CSV文件,返回二维列表
with open(filepath) as fo:
csv_obj = csv.reader(fo)
return [g for g in csv_obj]
def write_csv(lists,path):#二维列表写入CSV文件
with open(path,'w', newline='') as rs:
writer = csv.writer(rs)
writer.writerows(lists)
def main():
li_two = csv2list('two.csv')
li_one = csv2list('one.csv')
for g in li_two[1:]:#因为待比较的两个文件的列,其列名相同,所以从第二行开始
for i in li_one:
if g[2] in i[2]:
i.append(g[3])
continue
li_one[0].append('列4')#在one.csv的标题行新增一列,对应追加数据
write_csv(li_one,'result.csv')
if __name__ == __main__:
main()