使用不带引号的python csv writer [英] Using python csv writer without quotations

查看:245
本文介绍了使用不带引号的python csv writer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将如下所示的字符串列表写入到由给定分隔符分隔的文件中.

I'm trying to write a list of strings like below to a file separated by the given delimiter.

res = [u'123', u'hello world']

当我尝试按TAB拆分时,如下所示,它为我提供了格式正确的字符串.

When I try splitting by TAB like below it gives me the correctly formatted string.

writer = csv.writer(sys.stdout, delimiter="\t")
writer.writerow(res)

gives --> 123   hello world

但是当我尝试使用delimiter=" "按空格分割时,它给了我空间,但带有如下引号.

But when I try to split by space using delimiter=" ", it gives me the space but with quotation marks like below.

123 "hello world"

如何删除引号.这样当我使用空格作为分隔符时,我应该得到 123 hello world.

How do I remove quotation marks. So that when I use space as the delimiter I should get 123 hello world.

EIDT :当我尝试使用转义符时,它不会产生任何双引号.但是在我的测试数据中的每一个地方都出现了一个空格,使它加倍.

EIDT: when I try using the escapechar it doesn't make any double quotes. But everywhere in my testdata it appears a space, it makes it double.

推荐答案

报价行为由各种 quoting (或者,如果您喜欢用这种方式做,请在Dialect对象上设置).默认设置为QUOTE_MINIMAL,除非值包含分隔符,引号字符或行终止符,否则它将不会产生您正在描述的行为.仔细检查您的测试数据-[u'123', u'hello']不会产生您所描述的内容,但[u'123', u' hello']会产生您的描述.

Quoting behavior is controlled by the various quoting arguments provided to the writer (or set on the Dialect object if you prefer to do things that way). The default setting is QUOTE_MINIMAL, which will not produce the behavior you're describing unless a value contains your delimiter character, quote character, or line terminator character. Doublecheck your test data - [u'123', u'hello'] won't produce what you describe, but [u'123', u' hello'] would.

如果确定这是您想要的行为,则可以指定QUOTE_NONE,在这种情况下,如果您设置了

You can specify QUOTE_NONE if you're sure that's the behavior you want, in which case it'll either try to escape instances of your delimiter character if you set an escape character, or raise an exception if you don't.

这篇关于使用不带引号的python csv writer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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