如何为“分隔符"指定2个字符使用csv模块? [英] How to give 2 characters for "delimiter" using csv module?

查看:291
本文介绍了如何为“分隔符"指定2个字符使用csv模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用定界符'@ | @'生成csv,但是无法通过下面的代码来实现.

I'm trying to generate the csv with delimiter '@|@' but, I couldn't achieve through below code.

import csv
ifile  = open('test.csv', "rb")
reader = csv.reader(ifile)
ofile  = open('ttest.csv', "wb")
writer = csv.writer(ofile, delimiter='|', quotechar='"', quoting=csv.QUOTE_ALL)
for row in reader:
    writer.writerow(row)
ifile.close()
ofile.close()

在运行时,它已抛出以下错误.

While running, It has thrown below error.

Traceback (most recent call last):

File "csvfile.py", line 6, in <module>
writer = csv.writer(ofile, delimiter='@|@', quotechar='"', quoting=csv.QUOTE_ALL)
TypeError: "delimiter" must be an 1-character string

我该如何实现?

推荐答案

寿命太短,只需使用pandas

import pandas as pd
df.to_csv('output.csv', sep='|')

默认情况下,分隔符为',',这就是为什么将其称为Commasv的原因.但是通过将sep更改为'|',您可以轻松实现所需的目标.

By default, the delimiator is ',', that is why it is called Commasv. But by changing the sep to '|', you could simply achieve what you want.

这篇关于如何为“分隔符"指定2个字符使用csv模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆