0

I have a problems when writing special string to CSV.

Problem Solved:

def csv_write(s):
with open('test.csv', 'w', newline='', encoding='UTF-8') as f:
    writer = csv.writer(f, delimiter = ',')
    writer.writerow(s)
f.close()

def csv_read(path):
with open('test.csv', 'r', encoding='utf8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

csv_write(['Ngày tháng năm',''])

csv_read('test.csv')

Thank for all.

2 Answers2

1

Your code is working correctly. You are using a tool which displays the CSV in Latin-1 instead of UTF-8 and that's why it looks wrong.

tripleee
  • 175,061
  • 34
  • 275
  • 318
0

The default encoding scheme of python is UTF-8. The text mentioned here is in UTF-8 encoding. If you try to open the file in application which reads encoding as ASCII character, you will be displayed - Ngày tháng nÄm

Hover to the site and enter your UTF-8 string, you can see the ASCII will print the same. https://onlineutf8tools.com/convert-utf8-to-ascii

The program generates the correct output.

import csv


def test(s):
    with open('test.csv', 'w', newline='', encoding='utf8') as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerow(s)


test(['Ngày tháng năm', ''])

Above code outputs the same text in the program. Maybe you can try changing the Application through which you are reading the file.

Output

Ngày tháng năm,
Amar Kumar
  • 57
  • 8