为csv文件中的每个元素添加引号和制表符 [英] Adding quotes and a tab to each element in a csv file

查看:714
本文介绍了为csv文件中的每个元素添加引号和制表符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用python向csv文件中的每个元素添加引号和制表符?

例如,我要制作此csv示例:

TitleA,TitleB,TitleC,TitleD,TitleE,....
Data1,Data2,<null>,Data4,<null>,....
DataX,<null>,<null>,DataY,<null>,....

看起来像这样:

"TitleA"    "TitleB"    "TitleC"    "TitleD"    "TitleE"   ....
"Data1"    "Data2"    "<null>"    "Data4"    "<null>"    ....
"DataX"    "<null>"    "<null>"    "DataY"    "<null>"    ....

我实际上是将csv文件转换为制表符分隔的文件,其中所有元素都用单引号引起来...

有快速的方法可以做到这一点吗?

感谢您的帮助!

解决方案

您正在做的是将一种CSV方言转换为另一种,对吗?

因此,您可以通过定义两个CSV方言并为其中一个创建阅读器,为另一个创建书写器来实现.

幸运的是,这些方言都很简单(输入甚至是默认值),您不需要做任何花哨的事情:

with open('in.csv', 'r') as infile, open('out.csv', 'w') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile, delimiter='\t', quoting=csv.QUOTE_ALL)
    writer.writerows(reader)

在非常老的Python版本中,您可能必须将最后一行替换为两个:

    for line in reader:
        writer.writerow(line)

有关更多详细信息,请参见方言和格式参数./p>

How can I add quotes and a tab to every element in a csv file using python?

For example, I want to make this csv sample:

TitleA,TitleB,TitleC,TitleD,TitleE,....
Data1,Data2,<null>,Data4,<null>,....
DataX,<null>,<null>,DataY,<null>,....

Look like this:

"TitleA"    "TitleB"    "TitleC"    "TitleD"    "TitleE"   ....
"Data1"    "Data2"    "<null>"    "Data4"    "<null>"    ....
"DataX"    "<null>"    "<null>"    "DataY"    "<null>"    ....

I am essentially converting a csv file into a tab separated file where all the elements are enclosed in single quotes...

Is there a quick method to do this?

Any help is appreciated!

解决方案

What you're doing is converting from one CSV dialect to another, right?

So, you do that by defining two CSV dialects, and creating a reader for one and a writer for the other.

And fortunately, these dialects are both simple enough (the input is even the default) that you don't need to do anything fancy:

with open('in.csv', 'r') as infile, open('out.csv', 'w') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile, delimiter='\t', quoting=csv.QUOTE_ALL)
    writer.writerows(reader)

In very old versions of Python, you may have to replace that last line with two:

    for line in reader:
        writer.writerow(line)

See Dialects and Formatting Parameters for further details.

这篇关于为csv文件中的每个元素添加引号和制表符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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