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

Python实现按首字符拆分含内嵌逗号的CSV文件

当然可以!你的需求核心是只按第一个逗号拆分每条记录,同时处理原始文件里多条记录挤在一行的情况,我给你两种实现方案,纯Python原生和用pandas的,都能完美解决问题:

方案一:纯Python原生处理(无需额外库)

这种方法适合不想安装第三方库的场景,步骤清晰:

# 读取你的CSV文件,替换成你的实际文件名
with open('your_input.csv', 'r', encoding='utf-8') as input_file:
    # 读取整个文件的原始内容
    raw_content = input_file.read().strip()

# 把原始内容里的" 0,"替换成换行+0,将挤在一行的多条记录拆分成单独行
individual_records = raw_content.replace(' 0,', '\n0,').split('\n')

# 处理每条记录,拆分出目标两列
final_data = []
for record in individual_records:
    # 只拆分第一个逗号,确保后面的内嵌逗号不会被分割
    if ',' in record:
        column1, column2 = record.split(',', 1)
        # 去除第二列开头的空格,让结果更整洁
        column2 = column2.strip()
        final_data.append( (column1, column2) )

# 打印验证处理后的结果
for col1, col2 in final_data:
    print(f"{col1} ---- {col2}")

# 写入新的格式化CSV文件
with open('your_output.csv', 'w', encoding='utf-8', newline='') as output_file:
    # 先写入表头
    output_file.write('Column1,Column2\n')
    for col1, col2 in final_data:
        # 用双引号包裹内容,避免第二列的内嵌逗号破坏CSV格式
        output_file.write(f'"{col1}","{col2}"\n')

方案二:用Pandas快速处理(更简洁高效)

如果你已经在用Pandas做数据处理,这个方法会更省心:

import pandas as pd

# 读取原始文件内容
with open('your_input.csv', 'r', encoding='utf-8') as f:
    raw_content = f.read().strip()

# 拆分出单独的每条记录
records = raw_content.replace(' 0,', '\n0,').split('\n')

# 转换为DataFrame,自动拆分第一列和第二列
df = pd.DataFrame(
    [rec.split(',', 1) for rec in records if ',' in rec],
    columns=['Column1', 'Column2']
)

# 清理第二列的前导空格
df['Column2'] = df['Column2'].str.strip()

# 查看处理后的结果
print(df)

# 保存为新的CSV文件,自动处理内嵌逗号的引号问题
df.to_csv('your_output_pandas.csv', index=False, encoding='utf-8', quoting=1)

关键逻辑说明

  1. 拆分记录:原始文件里所有记录挤在一行,用" 0,"作为分隔符替换成换行,把每条记录单独分开;
  2. 拆分列:用split(',', 1)只拆分第一个逗号,这样后面的内嵌逗号会完整保留在第二列里;
  3. 格式兼容:写入新CSV时用双引号包裹内容,确保内嵌逗号不会导致CSV解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:34:05