Python CSV行存在性判断异常:已存在行被误判为不存在
CSV行匹配失败:明明存在却判定不存在的修复方案
问题描述
我想把CSV里的现有行和当前获取的软件信息行做匹配,存在就提示已存在,不存在就提示不存在,但现在不管行存不存在,脚本都判定不存在。我的代码如下:
# Imports from Library(s) from pathlib import Path import csv from windows_tools.installed_software import get_installed_software # Check if the csv file exists - if not: create it path = Path('./programms.csv') existingFile = [] if path.is_file() is not True: with open('programms.csv', 'w', newline='') as write1: w_object = csv.writer(write1) w_object.writerow(["Name", "Version", "Publisher"]) write1.close() # Lists all Software on the computer for software in get_installed_software(): csv_list = (software['name'], software['version'], software['publisher']) with open('programms.csv', 'r') as f1: existingFile = [line for line in csv.reader(f1, delimiter=',')] f1.close() #Checks if if csv_list in existingFile: print(str(csv_list) + "already is in the list") continue if csv_list not in existingFile: print("Current Object is not in the Existing lines") # # Open our existing CSV file in append mode # # Create a file object for this file # with open('programms.csv', 'a', newline='') as append1: # # Pass this file object to csv.writer() and create writer_object # writer_object = csv.writer(append1) # # Pass the list as an argument intothe writerow() # writer_object.writerow(csv_list) # # Close the file object # append1.close() print (existingFile)
我试过用if str(csv_list) in list(existingFile):来判断,但还是不行,作为Python新手不知道怎么解决。
问题根源
- 类型不匹配:
csv.reader读取的每一行是列表(比如["Chrome", "118.0.5993.89", "Google LLC"]),而你的csv_list是元组(比如("Chrome", "118.0.5993.89", "Google LLC")),列表和元组是不同的Python类型,直接用in判断会返回False。 - 重复读取CSV:每次循环都重新打开读取CSV,不仅效率低,还可能因为文件内容变化导致判断出错。
- 未排除表头:CSV的第一行是表头
["Name", "Version", "Publisher"],表头本身不是软件数据,应该跳过,否则可能干扰判断逻辑。 - 空白字符问题:软件名称、版本可能存在前后空格,比如CSV里是
"Chrome ",而获取到的是"Chrome",也会导致匹配失败。
修复方案
步骤1:提前读取CSV内容并处理
在循环获取软件信息之前,一次性读取CSV的所有行,转成元组(和csv_list类型一致),同时排除表头,还可以去掉每个字段的空白字符。
步骤2:统一类型并处理空白
把读取到的每一行转成元组,并且对每个字段执行strip()去除前后空格;同时对当前软件信息的每个字段也做同样处理,避免空白导致的不匹配。
步骤3:优化文件操作逻辑
不要每次循环都打开CSV,只在需要追加的时候打开一次,并且追加后更新已存在的条目列表,避免后续重复判断出错。
修复后的完整代码
from pathlib import Path import csv from windows_tools.installed_software import get_installed_software # 检查并创建CSV文件(如果不存在) path = Path('./programms.csv') if not path.is_file(): with open('programms.csv', 'w', newline='') as write1: w_object = csv.writer(write1) w_object.writerow(["Name", "Version", "Publisher"]) # 提前读取CSV中已有的软件数据,处理成元组并去掉空白,排除表头 existing_entries = [] with open('programms.csv', 'r') as f1: reader = csv.reader(f1, delimiter=',') next(reader) # 跳过表头行 for line in reader: # 去除每个字段的前后空白,转成元组 cleaned_line = tuple(field.strip() for field in line) existing_entries.append(cleaned_line) # 遍历所有已安装软件 for software in get_installed_software(): # 处理当前软件信息,去除空白并转成元组 current_entry = ( software['name'].strip(), software['version'].strip(), software['publisher'].strip() ) if current_entry in existing_entries: print(f"{current_entry} 已经在列表中") continue print(f"{current_entry} 不在现有列表中") # 以下是追加写入的代码(如果需要启用) # with open('programms.csv', 'a', newline='') as append1: # writer_object = csv.writer(append1) # writer_object.writerow(current_entry) # # 追加后要更新existing_entries,避免后续重复判断 # existing_entries.append(current_entry) print(existing_entries)
关键修复点解释
- 提前读取CSV:只读取一次,提升效率,同时保证判断时用的是同一套数据。
- 类型统一:把所有行都转成元组,和
current_entry类型一致,确保in判断有效。 - 空白处理:用
strip()去除每个字段的前后空格,避免因空格导致的匹配失败。 - 跳过表头:用
next(reader)跳过第一行的表头,避免把表头当成软件数据判断。
内容的提问来源于stack exchange,提问作者Pr3adus
相关产品推荐
相关产品推荐

