Loading Japanese Characters in Python 2.7 CSV Files

Asked 2 years ago, Updated 2 years ago, 85 views

import csv

with open('datas.csv', 'r') ascsv_file:
    csv_reader=csv.reader(csv_file)

    for line incsv_reader:
        print(line)

Now I'm putting in the file, but once I run the code,

'2018\x94N12\x8c\x8e30\x93\xfa(\x93\xfa)'

This is coming out.Is there an ENCODE method for CSV files?

python python2

2022-09-29 22:50

2 Answers

Specify the encoding when open the file.
If not specified, it becomes the default encoding for the OS system and is garbled.

import csv
import codecs

# Load with encoding
with codecs.open('datas.csv', 'r', 'shift_jis') ascsv_file:
# 3.x and later can be described below.
# with open('datas.csv', 'r', encoding="shift_jis") ascsv_file:
    csv_reader=csv.reader(csv_file)
    for line incsv_reader:
        print(line)


2022-09-29 22:50

Decode the lines you read from shift_jis.

import csv
import codecs

with open('datas.csv', 'r') ascsv_file:
    csv_reader=csv.reader(csv_file)
    for line incsv_reader:
        line = [codecs.decode(s, 'shift_jis') for inline] # Decode read lines from shift_jis
        print(line)
        For s in line:
            print(s)


2022-09-29 22:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.