imoum
imoum

Reputation: 423

how to handle with string while writing in csv file with python

enter image description herei'm trying to write in csv file i have two value in my list [string,int] and this is my code

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

but i get 'enveloppes' in row then esquisse in other row not all the string in one row can anyone help me ? my csv file should contain two rows, one for 'Enveloppes Esquisse adh\xe9sives' and one for '1,85'

Upvotes: 1

Views: 752

Answers (1)

Viktor Kerkez
Viktor Kerkez

Reputation: 46596

The documentation say:

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.

Since your strings are either cp1250 or cp1252 (I cannot tell from the sample) encoded byte string and not unicode strings, that's should be OK. You should just open your file in binary mode:

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)

Upvotes: 2

Related Questions