CSV变量匹配校验异常:代码无报错但结果始终显示未找到
CSV匹配指定变量始终返回"not there"?问题出在遍历对象上!
需求:检查CSV文件中是否存在与指定变量匹配的值,若存在则输出'variable present'(实际代码中写的是"already there")
用户尝试遍历CSV的每一行及行内每个字段进行匹配校验,代码无报错,但结果始终为负,仅输出'not there'。
测试代码:import csv old_name = "random name already present in the table" with open("data.csv", "r") as csv_file: fieldnames = ["name", "price"] csv_reader = csv.DictReader(csv_file, fieldnames=fieldnames) for row in csv_reader: for field in row: if field == old_name: print("already there") else: print("not there")输出结果:表格中每个条目均显示'not there'。
问题根源
你踩了一个很容易忽略的小坑——你遍历的是字典的键,而不是键对应的值!
当你用for field in row:遍历csv.DictReader返回的行字典时,field拿到的是字段名(也就是你指定的"name"、"price"),而不是每行中对应字段的实际内容。拿字段名和你的old_name(一个具体的名字字符串)对比,当然永远不相等,所以每次都会走到else分支输出"not there"。
修正后的代码
我们需要遍历行字典的值,同时优化逻辑避免重复输出冗余信息:
import csv old_name = "random name already present in the table" # 标记是否找到匹配项 found = False with open("data.csv", "r") as csv_file: fieldnames = ["name", "price"] csv_reader = csv.DictReader(csv_file, fieldnames=fieldnames) for row in csv_reader: # 遍历当前行的所有字段值 for value in row.values(): # 加strip()避免CSV中首尾空格导致匹配失败 if value.strip() == old_name.strip(): print("already there") found = True break # 找到匹配就跳出内层循环 if found: break # 找到匹配就直接结束外层循环,不用继续遍历 # 仅当完全遍历后未找到匹配时输出提示 if not found: print("not there")
额外优化说明
- 加入
strip()是为了规避CSV单元格中可能存在的首尾空格(比如内容是" random name already present in the table ")导致的匹配失败 - 加入
found标记和循环中断,找到匹配后立即停止遍历,提升大文件处理效率 - 调整输出逻辑,避免每遍历一个字段就输出一次,仅在关键节点输出结果
内容的提问来源于stack exchange,提问作者Lukas Kunibert
相关产品推荐
相关产品推荐

