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

如何用Python提取CSV数据并写入目标CSV(过滤指定行)

解决方案:CSV数据提取与筛选写入

方法1:使用Python内置csv模块(无需第三方库)

直接用标准库处理,逻辑清晰且无依赖:

import csv

# 替换为你的源文件和目标文件路径
source_path = "biometrics_source.csv"
target_path = "customer_target.csv"

with open(source_path, mode='r', newline='', encoding='utf-8') as source_file, \
     open(target_path, mode='w', newline='', encoding='utf-8') as target_file:
    
    reader = csv.DictReader(source_file)
    writer = csv.DictWriter(target_file, fieldnames=reader.fieldnames)
    
    # 写入表头
    writer.writeheader()
    
    # 遍历筛选并写入
    for row in reader:
        # 若Status列是字符串格式(如"True"/"False"),用此判断
        if row['Status'].strip().lower() == 'true':
            writer.writerow(row)
        # 若Status是原生布尔值,替换为下面的判断:
        # if row['Status']:
        #     writer.writerow(row)

关键注意点:

  • 先确认Status列的实际格式:CSV导出时布尔值常被存为字符串,需用字符串匹配;若为原生布尔值直接判断即可。
  • 加newline=''避免Windows环境下写入出现空行。
  • 指定编码(如utf-8)防止乱码。

方法2:修复pandas报错并实现需求

如果之前用pandas出错,大概率是路径、编码或数据类型问题,修复后即可正常使用:

import pandas as pd

# 读取源文件(解决编码/路径问题)
df = pd.read_csv("biometrics_source.csv", encoding='utf-8')

# 筛选Status为True的行(根据实际数据类型调整)
# 情况1:Status是字符串类型(如"True"/"False")
filtered_df = df[df['Status'].str.strip().str.lower() == 'true']
# 情况2:Status是布尔值类型
# filtered_df = df[df['Status']]

# 写入目标文件(解决索引/空行问题)
filtered_df.to_csv("customer_target.csv", index=False, encoding='utf-8', newline='')

常见报错对应修复:

  • KeyError: 'Status':用print(df.columns)查看源文件列名,确认是否存在大小写、空格差异(比如是status或Status)。
  • UnicodeDecodeError:读取时替换编码参数为gbk或utf-8-sig。
  • 筛选无结果:用df['Status'].dtype查看列类型,调整筛选逻辑。
  • 写入空行:添加newline=''参数(仅Windows环境需要)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 02:33:12