You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3对比两个CSV文件不同行 筛选指定列匹配结果生成新CSV

解决方案

原代码错误原因

  • 未正确拆分CSV行的列:直接迭代文件对象得到的是每行的完整字符串,不是拆分后的列数组,row[0]/row[6]实际取的是字符串的第1/7个字符,而非对应列的值
  • 丢失了原始行内容:读取updatedmembers.csv时仅提取了邮箱存入set,没有保留完整行信息,最终只能输出邮箱无法输出完整行
  • 未处理行尾换行符:直接读取的每行末尾会携带换行符,不处理会导致匹配失败

正确实现代码

推荐使用Python内置的csv模块处理CSV文件,避免带逗号的引号字段等边界格式问题:

import csv

# 读取旧成员邮箱存入集合,方便后续快速匹配
prev_emails = set()
with open('previousmembers.csv', 'r', encoding='utf-8', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        if row:
            prev_emails.add(row[0].strip())

# 遍历更新后的成员表,筛选符合条件的行写入新文件
with open('updatedmembers.csv', 'r', encoding='utf-8', newline='') as in_f, \
     open('newfolks.csv', 'w', encoding='utf-8', newline='') as out_f:
    reader = csv.reader(in_f)
    writer = csv.writer(out_f)
    for row in reader:
        if not row:
            continue
        current_email = row[6].strip()
        if current_email not in prev_emails:
            writer.writerow(row)

如果你的CSV无特殊格式(没有带逗号的引号字段),也可以用字符串拆分的极简写法:

# 读取旧邮箱集合
with open('previousmembers.csv', 'r', encoding='utf-8') as f:
    prev_emails = {line.strip() for line in f if line.strip()}

# 筛选并写入新文件
with open('updatedmembers.csv', 'r', encoding='utf-8') as in_f, \
     open('newfolks.csv', 'w', encoding='utf-8') as out_f:
    for line in in_f:
        line = line.strip()
        if not line:
            continue
        parts = line.split(',')
        if parts[6].strip() not in prev_emails:
            out_f.write(line + '\n')

两种写法运行后都会生成符合要求的newfolks.csv文件。

内容的提问来源于stack exchange,提问作者user247365

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 13:36:04