Skip to main content
 首页 » 编程设计

python之根据另一个 csv 中的另一个值在 csv 列中写入一个值

2025年05月04日9zhujiabin

我正在尝试搜索 csv 文件中特定列中的所有行,以查看它们是否包含另一个 csv 文件中的字符串。如果它们包含该字符串,我想将相应的值写入另一个特定列。

例如文件1:

Search Value,Location 
UK,United Kingdom 
United Kingdom,United Kingdom 
United States,United States 
Hong Kong,Hong Kong 
Florida,"Florida, United States" 

和文件2:

Name,Default,Geo Location 
DRE UK,, 
Production United States,, 
Development Hong Kong,, 
United Kingdom Sales,, 
Florida Marketing,, 

我想找到文件 2 中名称包含文件 1 中搜索值字符串的行,然后将文件 1 中位置的相应值写入文件 2 中的地理位置。所以结果是这样的:

Name,Default,Geo Location 
DRE UK,,United Kingdom 
Production United States,,United States 
Development Hong Kong,,Hong Kong 
United Kingdom Sales,,United Kingdom 
Florida Marketing,,"Florida, United States" 

我正在寻找答案,然后遇到了 loop through rows of one csv file to find corresponding data in another .我以此为基础开始编写代码,但我不知道这是否正确,我被卡住了。

import csv 
 
file1reader = csv.reader(open('file1.csv','rb')) 
file2reader = csv.reader(open('file2.csv','rb')) 
writer=csv.writer(open('file3.csv','wb')) 
 
header1 = file1reader.next() #header 
header2 = file2reader.next() #header 
 
 
for Search Value, Location in file1reader: 
    for Name, Default, Geo Location in file2reader: 
        if Search Value in Name: # found it 

提供的数据是我想做的事的一个例子。实际文件会很大,所以请记住这一点。

感谢任何帮助。

编辑

如果我想在最终输出 (file3.csv) 中包含 file2.csv 中不符合条件的原始行,我该怎么做?

例如,如果 file2 是这样的,而我也希望包含不匹配的行:

Name,Default,Geo Location 
DRE UK,, 
Production United States,, 
Development Hong Kong,, 
United Kingdom Sales,, 
Florida Marketing,, 
Stuff,,Somewhere 
More Stuff,, 

请您参考如下方法:

这是一个使用 DictReader 的简单示例和 DictWriter类:

from csv import DictReader, DictWriter 
 
with open('file1.csv') as fin1,\ 
     open('file2.csv') as fin2,\ 
     open('file3.csv', 'wb') as fout: 
 
    reader1 = DictReader(fin1) 
    reader2 = DictReader(fin2) 
 
    writer = DictWriter(fout, fieldnames=reader2.fieldnames) 
    writer.writeheader() 
 
    for line2 in reader2: 
        outline = dict(line2) 
        fin1.seek(0) # resets the reader1 iterator 
        for line1 in reader1: 
            if line1['Search Value'] in line2['Name']: 
                outline['Geo Location'] = line1['Location'] 
        writer.writerow(outline) 

这个算法的复杂度是O(n2),所以,像@maged指出,它不是很有效。