更改分隔符时在数据中保留逗号

2024-06-28 19:19:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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

实际数据文件enter image description here的屏幕截图


Tags: csvthenametitletypeproductrecordnow
2条回答

虽然我同意熊猫是一个非常有用的软件包,但我还是会选择你所拥有的(包括我的变化):

from csv import reader, writer, QUOTE_MINIMAL

with open(filein, encoding='utf-8') as in_fd,
     open('Detail_Test_Piped.csv', 'wt', encoding='utf-8') as out_fd:
    csv_read = reader(in_fd)  # Using defaults
    csv_write = writer(out_fd, delimiter='|', quotechar='"', quoting=QUOTE_MINIMAL)
    csv_write.writerows(csv_read)

我不知道它是否算是一种“优势”,但它“开箱即用”,无需安装第三方软件包

为什么不利用熊猫来完成这项任务呢

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

enter image description here

相关问题 更多 >