python - Can anyone explain this error? AttributeError: 'list' object has no attribute 'encode' -


from research i've been doing, code should write text csv file.

import csv name = "x" score = "y" open('some.csv', 'wb') f:     writer = csv.writer(f)     data = [["name", "score"],             [name,score]]     f.write(data[0].encode('utf-8'))             writer.writerows(data) 

at first, threw me encoding error. after hunting around on stack overflow, found needing encode text utf8. tried encoding x.encode(). got this:

f.write(data[0].encode('utf-8')) attributeerror: 'list' object has no attribute 'encode' 

i can't find answer why happening. can explain why i'm getting error?

use csv writer created. don't write f directly. drop f.write line:

import csv name = "x" score = "y" open('some.csv', 'wb') f:     writer = csv.writer(f)     data = [["name", "score"],             [name,score]]     writer.writerows(data) 

content of some.csv:

name,score x,y 

note assuming python 2. if on python 3, , writing non-ascii characters, open has different parameters.

#coding:utf8 import csv name = "马克" score = "y" open('some.csv', 'w', encoding='utf8', newline='') f:     writer = csv.writer(f)     data = [["name", "score"],             [name,score]]     writer.writerows(data) 

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -