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

Python读取CSV提取Virginia数据写入后输出文件为空问题排查

故障原因
  • 写入参数错误:代码中writer.writerow(row)传入的row是行索引整数,并非拆分后的行内容列表,正确参数应为contents[row]。
  • 逻辑冗余:内层for word in range(len(contents[row]))循环无实际作用,匹配逻辑未使用word变量,不仅拖慢运行效率,匹配成功后还会重复写入同一行。
  • 处理方式不规范:直接用split(',')拆分CSV行,遇到字段内含逗号的场景会拆分错误,使用csv.reader处理输入更稳妥。
  • 表头丢失:现有逻辑未保留原CSV的表头,生成的文件没有字段说明。
修复后代码
import csv

input_file = 'all.csv'
output_file = 'Virginia.csv'
state = 'Virginia'

def extract_records_for_state(input_file, output_file, state):
    with open(input_file, 'r', newline='', encoding='utf-8') as infile:
        reader = csv.reader(infile)
        # 读取表头
        header = next(reader)
        with open(output_file, 'w', newline='', encoding='utf-8') as outfile:
            writer = csv.writer(outfile)
            # 写入表头
            writer.writerow(header)
            for row in reader:
                # 第三列为州名,匹配成功则写入
                if len(row) >= 3 and row[2] == state:
                    writer.writerow(row)

extract_records_for_state(input_file, output_file, state)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:57:03