python - 使用python写入csv文件时如何处理字符串

标签 python csv

enter image description here我正在尝试写入 csv 文件,我的列表中有两个值 [string,int],这是我的代码

prod = [['Enveloppes Esquisse adh\xe9sives', 1.85], 
        ['Enveloppes adh\xe9sives Esquisse', 1.1], 
        ['Enveloppes adh\xe9sives Esquisse', 1.1], 
        ['Enveloppes adh\xe9sives Esquisse', 1.85], 
        ['Pochettes kraft Esquisse', 0.95], 
        ['Pochettes kraft Esquisse', 1.75]]

cw = csv.writer(open("nv.csv", 'w'), delimiter=';')
    cw.writerow(['Produit', 'Prix'])
    for row in prod:
        cw.writerow( [row[0],row[1]] )

但我在行中得到“信封”,然后在另一行中得到esquisse,而不是一行中的所有字符串 谁能帮我 ? 我的 csv 文件应包含两行,一行代表“Enveloppes Esquisse adh\xe9sives”,另一行代表“1,85”

最佳答案

文档说:

The csv module doesn’t directly support reading and writing Unicode, but it is 8-bit-clean save for some problems with ASCII NUL characters. So you can write functions or classes that handle the encoding and decoding for you as long as you avoid encodings like UTF-16 that use NULs. UTF-8 is recommended.

由于您的字符串是 cp1250cp1252 (我无法从示例中看出)编码的字节字符串而不是 unicode 字符串,所以应该没问题。您应该以二进制模式打开文件:

import io
import csv
prod = [['Enveloppes Esquisse adh\xe9sives', 1.85],
        ['Enveloppes adh\xe9sives Esquisse', 1.1],
        ['Enveloppes adh\xe9sives Esquisse', 1.1],
        ['Enveloppes adh\xe9sives Esquisse', 1.85],
        ['Pochettes kraft Esquisse', 0.95],
        ['Pochettes kraft Esquisse', 1.75]
        ]

with io.open('nv.csv', 'wb') as f:
    writer = csv.writer(f, delimiter=';')
    writer.writerow(['Produit', 'Prix'])
    for row in prod:
        writer.writerow(row)

关于python - 使用python写入csv文件时如何处理字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18481986/

相关文章:

python - 在 Python 的 csv 字典中创建字典列表

python - 使用 Python 读取 csv 时将字节解析为 str

python - 使用 PySDL2 捕捉操纵杆事件

python - 使用 dict 对 SQL 插入进行字符串格式化

python - 在 sqlalchemy ORM 查询中使用 NOT EXISTS 子句

python - 从维基百科页面获取所有链接

python - 如何使用 Python Pandas 将 CSV 文件写入 XLSX?

c - 在 C 中将 csv 文件读取到结构体

python - 如何修复名称错误: name 'X_train' is not defined?

arrays - 从CSV列表创建数组