python - 将一个 CSV 作为查找与另一个 CSV 进行比较时,1<>1 何时出现?
问题描述
我想使用 file1.csv 作为 file2.csv 的查找。出现的任何内容都应从 file2.csv 打印整行。
但是,当我遍历 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'
解决方案
您可以稍微重构一下代码:
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']
阅读:
推荐阅读
- python-3.x - RL-Coach - 如何使用自定义预设?
- javascript - Ajax 时区服务
- javafx - 从列表属性到任意对象属性的 javafx 绑定
- python - 使用 {{ var }} 在 Python Flask 中运行 HTML 代码
- python - 在python中将一个范围分成n个大小相等的部分
- javascript - Material UI 3.9.3 复选框样式未在 IE 中设置
- android - 如何在日期选择器对话框android中更改年份和摘要文本大小
- ruby-on-rails - 将样式应用于 Rails 中的链接
- json - Flutter 将 JSON 流 List 转换为 Map 对象
- blockchain - 找不到构建 go-ethereum 的软件包