Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to read csv file using python27, but there is an error like" TypeError: 'encoding' is an invalid keyword argument for this function"

here is my code:

import csv
file  = open('traintag1.csv','r',encoding='utf-8')
csv_reader = csv.reader(file)
for row in csv_reader:
    print row[-2]

then encounter an error like the title:

file = open('traintag1.csv','r',encoding='utf-8') TypeError: 'encoding' is an invalid keyword argument for this function"

I wanna use 'encoding='utf-8' because when the file is full of Chinese, after reading file to print on screen the words are messy. and when I add another linefrom io import open on the head, there again an error like this:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xbb in position 29: invalid start byte

like image 746
L.Elizabeth Avatar asked Mar 21 '17 02:03

L.Elizabeth


1 Answers

Use codecs to open the file, this allows an encoding to be specified, for example:

import csv
import codecs

with codecs.open('traintag1.csv', 'rb', encoding="utf-8") as f_input:
    csv_reader = csv.reader(f_input)

    for row in csv_reader:
        print row[-2]
like image 66
Martin Evans Avatar answered Oct 14 '22 04:10

Martin Evans