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

Python遍历CSV文件时,如何避免拆分带逗号的引号字段?

正确拆分含带逗号引号字段的CSV数据

当处理包含带逗号的引号字段(比如"1,506")的CSV数据时,直接用split(',')会把这类字段错误拆分,导致数据结构混乱。

问题示例

原CSV行:

NA,ShimmyXD,#NA1,Radiant,135.8,992,24.9,0,140,80,161,"1,506","1,408",703,1.07,0.7,29,208.8,59,59.6,Fade,Viper,Omen,Vandal,35,59,5,802,Phantom,33,62,5,220,Classic,36,60,3,147

错误拆分结果(用split(',')):

['NA', 'ShimmyXD', '#NA1', 'Radiant', '135.8', '992', '24.9', '0', '140', '80', '161', '"1', '506"', '"1', '408"', '703', '1.07', '0.7', '29', '208.8', '59', '59.6', 'Fade', 'Viper', 'Omen', 'Vandal', '35', '59', '5', '802', 'Phantom', '33', '62', '5', '220', 'Classic', '36', '60', '3', '147']

期望的正确拆分结果:

['NA', 'ShimmyXD', '#NA1', 'Radiant', '135.8', '992', '24.9', '0', '140', '80', '161', '"1,506"', '"1,408"', '703', '1.07', '0.7', '29', '208.8', '59', '59.6', 'Fade', 'Viper', 'Omen', 'Vandal', '35', '59', '5', '802', 'Phantom', '33', '62', '5', '220', 'Classic', '36', '60', '3', '147']

解决方案:使用Python标准库csv模块

不要手动用split(',')处理CSV,csv模块原生支持解析带引号的字段,能自动识别并保留这类字段的完整性。

修改后的代码:

import csv

def ValorantDoL(file):
    """
    Sorts data into Dictionary of List
    """
    Data = {}
    with open(file, 'r', encoding='UTF-8') as f:
        reader = csv.reader(f)
        headers = next(reader)  # 获取表头行
        # 初始化每个表头对应的空列表
        for header in headers:
            Data[header] = []
        # 遍历每一行数据,将字段对应到表头列表
        for row in reader:
            for header, value in zip(headers, row):
                Data[header].append(value)
    return Data

额外处理(可选)

如果需要去掉字段的引号,或者把带逗号的数字转换成纯数字,可在添加数据时做如下处理:

# 示例:清理字段并转换数字
cleaned_value = value.strip('"')
# 若为带逗号的数字,替换逗号后转为整数
if ',' in cleaned_value:
    try:
        cleaned_value = int(cleaned_value.replace(',', ''))
    except ValueError:
        # 转换失败则保留原字符串
        pass
Data[header].append(cleaned_value)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:10:37