首页 > 解决方案 > 在更改分隔符时保持数据中的逗号

问题描述

我有一个 csv 文件,我需要将分隔符更改为管道字符,但是我找不到调用 csv writer 以在数据中保留逗号的正确方法。

下面的示例数据:

Record Type, Participant Full Name, Product Title
N,"Calvin Harris, The Weekend", Over Now

当前脚本:

reader = csv.reader(open(filein,encoding='utf-8'), delimiter=',', quotechar='"')
writer = csv.writer(open('Detail_Test_Piped.csv', 'w',newline='',encoding='utf-8'), 
    delimiter='|',quotechar='"',quoting=csv.QUOTE_MINIMAL)

期望的输出:

Record Type|Participant Full Name|Product Title
N|Calvin Harris, The Weekend|Over Now

当前实际输出:

Record Type|Participant Full Name|Product Title
N|Calvin Harris|The Weekend|Over Now

实际数据文件截图在此处输入图像描述

标签: pythoncsv

解决方案


为什么不利用pandas来完成这项任务?

import pandas as pd
df = pd.read_csv('abc.csv')
df.to_csv('abc_piped.csv', sep='|')

在此处输入图像描述


推荐阅读