当将一个CSV作为查找与另一个CSV进行比较时,1何时<>1?

2024-04-19 06:12:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

2 sample data files

但是,当我在file2.csv的行中循环并评估对数据的查找时,我无法使line变量等于我的第二列(row1)。我好像少了什么?你知道吗

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'

Tags: csvinimportforislineopenfile1
1条回答
网友
1楼 · 发布于 2024-04-19 06:12:29

您可以稍微重新构造代码:

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.7):#删除()处的print使其更好

('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

相关问题 更多 >