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']

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

当我像下面这样按TAB拆分时,它会给我正确的格式化字符串。

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

gives --> 123   hello world

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

但是,当我尝试用分隔符=“”来分割空间时,它给了我空间,但是有下面的引号。

123 "hello world"

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

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

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.

当我尝试使用escapechar时,它不会发出任何双引号。但在我的testdata中,每一个地方都显示一个空格,这使它加倍。

3 个解决方案

#1


8

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_minimum,它不会产生您所描述的行为,除非一个值包含分隔符、引号字符或行终止符。双重检查你的测试数据——[u'123', u'hello']不会产生你所描述的,但是[u'123', u'hello']会。

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.

如果您确定这是您想要的行为,您可以指定QUOTE_NONE,在这种情况下,如果您设置了转义字符,它将尝试转义分隔符的实例,或者如果不设置转义字符,则引发异常。

更多相关文章

  1. Python正则表达式在分隔符之间查找特殊字符
  2. Python 用hashlib求中文字符串的MD5值
  3. 将字节列表转换为字节字符串
  4. [D]用python提取多段字符串该怎么写正则表达式。
  5. 如何用位于括号外的逗号分隔字符串?
  6. 用于搜索和替换大字符串的最快Python方法
  7. python 字符串操作
  8. 为什么Python的eval()拒绝这个多行字符串,我如何修复它?
  9. 第七章、Python字符编码

随机推荐

  1. android 用户注册demo
  2. android销毁Activity和被系统销毁时的数
  3. 【按键】灭屏后瞬间按返回键,可以点亮屏幕
  4. Shape属性详解
  5. android关于获取手机唯一码的组合文章
  6. 【android】get PatchStore::createDisab
  7. Android软键盘手动显示、隐藏、布局上移
  8. Android(安卓)TableLayout表格布局
  9. Android aapt 工具介绍(转载)
  10. Android 下载文件 显示进度条