python - 删除 CSV 输出中的 'b' 标志

标签 python csv

我正在尝试将输出写入 Python 3.4 中的 CSV 文件,但 CSV 文件始终包含“b”标志。例如,b'The text output1', b'The text output2',... 我想知道是否有办法摆脱 'b' 标志。我知道这不是 Python 2.X 中的问题。

这是我使用的代码

with open('test.csv', 'w') as f:
    writer = csv.DictWriter(f, ['field'], extrasaction='ignore')
    writer.writeheader()
    test_text = mongo.test.find({'text': text})
    for t in test_text
        writer.writerow({i:v.encode('utf') for i,v in t.items()})

非常感谢

------更新------------

非常感谢 Tim Pietzcker、John Zwinck 和 Warren Weckesser 提供的有用评论和答案。根据沃伦的建议,如果我将代码更改为

import csv

data = [chr(0x03d5) + 'oo', 'b' + chr(0x0101) + 'r']

with open('test.csv', 'w') as f:
    writer = csv.writer(f)
    for item in data:
        writer.writerow([item])

我会收到错误信息

UnicodeEncodeError: 'charmap' codec can't encode character '\u03d5' in position 0: character maps to <undefined>

如果我将代码更改为

import csv

data = [chr(0x03d5) + 'oo', 'b' + chr(0x0101) + 'r']

with open('test.csv', 'w') as f:
    writer = csv.writer(f)
    for item in data:
        writer.writerow([item.encode('utf')])

我将得到带有“b”标志的输出

b'\xcf\x95oo'
b'b\xc4\x81r'

关于这是如何发生的以及我如何能够解决它的任何想法?再次感谢。

------更新2------------

非常感谢 Warren 的解决方案。以下代码有效!

import csv

data = [chr(0x03d5) + 'oo', 'b' + chr(0x0101) + 'r']

with open('test.csv', 'w', encoding='utf8') as f:
    writer = csv.writer(f)
    for item in data:
        writer.writerow([item])

最佳答案

不要自己显式编码字符串;让作家来处理吧。例如,这段代码:

import csv

data = [chr(0x03d5) + 'oo', 'b' + chr(0x0101) + 'r']

with open('test.csv', 'w') as f:
    writer = csv.writer(f)
    for item in data:
        writer.writerow([item])

写入文件

ϕoo
bār

使用 UTF-8 编码(至少在我的系统上是这样,其中 locale.getpreferredencoding(False) 返回 'UTF-8')。要使编码显式化,您可以在对 open 的调用中设置编码:

    with open('test.csv', 'w', encoding='utf8') as f:

如果最后一行更改为 writer.writerow([item.encode('utf')])(将字符串转换为 bytes),它会生成

b'\xcf\x95oo'
b'b\xc4\x81r'

在您的示例中,尝试更改此行:

        writer.writerow({i:v.encode('utf') for i,v in t.items()})

为此:

        writer.writerow(t)

如果可行,您可以替换它:

    for t in test_text
        writer.writerow({i:v.encode('utf') for i,v in t.items()})

    writer.writerows(test_text)

关于python - 删除 CSV 输出中的 'b' 标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26228914/

相关文章:

Python导入模块只能在新的终端窗口中工作

python - 在python-Gurobi接口(interface)中添加惰性约束

python - 如何对我的 DataFrame 中的值进行分组和计数?

javascript - CSV 文件到数组

java - 使用java从sqlserver将大数据导出到CSV

java - 更新 CSV 文件中的特定行

python - 分配给 numpy 结构化数组

python - Flask-RESTful 与 Flask-WTF 表单集成

php - 将文本文件转换为 CSV 或将每个值存储在 mysql 中?

python - to_CSV 将 np.array 保存为字符串而不是列表