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

Python2.7 CSV匹配脚本故障排查:解析文件并导出匹配数据

嘿,我来帮你搞定这个Python 2.7的CSV匹配脚本问题!看你给出的代码片段,应该是卡在了读取11pmQuote.csv并匹配数据的环节,而且直接用open不关闭文件也容易出问题。我给你整理了完整的修复版本,还加了详细的解释:

修复后的完整脚本
import csv

# 先把11pmTrend.csv里的Symbol和Rank存进字典,方便快速查找
trend_symbol_rank = {}
with open("11pmTrend.csv", 'r') as trend_file:
    trend_reader = csv.DictReader(trend_file, delimiter=',')
    for row in trend_reader:
        symbol = row["Symbol"]
        trend_symbol_rank[symbol] = row["Rank"]

# 读取11pmQuote.csv,匹配Symbol并收集要输出的数据
result_rows = []
with open("11pmQuote.csv", 'r') as quote_file:
    quote_reader = csv.DictReader(quote_file, delimiter=',')
    for row in quote_reader:
        symbol = row["Symbol"]
        # 只处理在趋势文件里存在的股票
        if symbol in trend_symbol_rank:
            result_rows.append({
                "Rank": trend_symbol_rank[symbol],
                "Symbol": symbol,
                "CurrentPrice": row["CurrentPrice"]
            })

# 把结果写入11pm.csv
with open("11pm.csv", 'w') as output_file:
    # 指定输出的表头顺序
    output_fields = ["Rank", "Symbol", "CurrentPrice"]
    writer = csv.DictWriter(output_file, fieldnames=output_fields)
    # 写入表头
    writer.writeheader()
    # 批量写入所有匹配到的数据行
    writer.writerows(result_rows)

几个关键改进点:

  • 用with语句管理文件:Python 2.7里这样做会自动帮你关闭文件,避免忘记close()导致的资源泄漏或数据写入不完整的问题
  • 用字典存储趋势数据:把Symbol作为键、Rank作为值,后续匹配时能快速判断Symbol是否存在,比用集合更高效(还能直接拿到Rank)
  • 用csv.DictWriter写输出:比手动拼接字符串写行更规范,能自动处理CSV里的特殊字符(比如字段里有逗号的情况),也能保证表头和数据的顺序一致

额外注意事项:

  • 一定要确保两个输入CSV的表头完全匹配:比如Symbol、Rank、CurrentPrice的大小写、拼写不能错,否则会报KeyError
  • 如果你的CSV文件有编码问题(比如包含中文或非ASCII字符),可以用codecs模块来打开文件(Python 2.7的open不支持直接指定编码):
    import codecs
    with codecs.open("11pmTrend.csv", 'r', 'utf-8') as trend_file:
        # 后续读取逻辑不变
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:35:20