首页 > 解决方案 > 将一个 CSV 作为查找与另一个 CSV 进行比较时,1<>1 何时出现?

问题描述

我想使用 file1.csv 作为 file2.csv 的查找。出现的任何内容都应从 file2.csv 打印整行。

2个样本数据文件

但是,当我遍历 file2.csv 的行并评估我对数据的查找时,我无法使 line 变量等于我的第二列(第1行)。我似乎缺少什么?

import csv
import sys

file1 = 'file1.csv'
file2 = 'file2.csv'

appcode = []
with open(file1, "r") as f:
    f.readline()            # Skip the first line
    for line in f:
        appcode.append(str(line.strip("\n")))
        print('This is what we are looking for from file1 ...' +line)
        csv_file = csv.reader(open(file2, "rb"), delimiter=",")   # was rb

        #loop through csv list
        for row in csv_file:
            print('line = '+line +'   '+'row is... '+row[1])

            #if current rows 2nd value is equal to input, print that row
            if str(line) is str(row[1]):
                print row
            else:
                print 'thinks '+str(line)+'='+str(row[1])+' is false'

标签: pythoncsvlookup

解决方案


您可以稍微重构一下代码:

import csv
import sys

file1 = 'file1.csv'
file2 = 'file2.csv'

# create your files data:
with open(file1,"w") as f:
    f.write("""appname\n1\neee\naaa\n""")
with open(file2,"w") as f:
    f.write("""server,appname\nfrog,1\napple,aaa\n""")


# process files
with open(file1, "r") as f:
    f.readline()            # Skip the first line
    f_set = set(  (line.strip() for line in f) )
    # no need to indent the rest as well - you are done with reading file1

print('This is what we are looking for from file1 ...', f_set)

with open(file2,"r") as f:
    csv_file = csv.reader(f, delimiter=",")  
    #loop through csv list
    for row in csv_file:
        if row[1] in f_set: # check for a in b is fastest with sets
            print(row)
        else:
            pass  # do something else

通过检查row[1] in f_set,您可以避免错误的比较,使用is- 作为一般规则:仅当您真的想检查 2 个事物是否是相同的对象时才使用 - 而不是它们是否包含相同的事物。

输出 (2.7): # 去掉()atprint让它更好看

('This is what we are looking for from file1 ...', set(['1', 'eee', 'aaa']))
['frog', '1']
['apple', 'aaa']

输出(3.6):

This is what we are looking for from file1 ... {'1', 'aaa', 'eee'}
['frog', '1']
['apple', 'aaa']

阅读:

https://docs.python.org/2/library/sets.html


推荐阅读