Roughbladez
Roughbladez

Reputation: 61

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

From the research I've been doing, this code should write text into a CSV file.

import csv
name = "X"
score = "Y"
with open('some.csv', 'wb') as f:
    writer = csv.writer(f)
    data = [["Name", "Score"],
            [name,score]]
    f.write(data[0].encode('utf-8'))        
    writer.writerows(data)

At first, it threw me an encoding error. After hunting around on Stack Overflow, I found something about needing to encode the text into UTF8. So I tried encoding with X.encode(). Then I got this:

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

I can't find an answer as to why this is happening. Can anyone explain why I'm getting this error?

Upvotes: 0

Views: 21138

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177715

Use the csv writer you created. Don't write f directly. Drop the f.write line:

import csv
name = "X"
score = "Y"
with open('some.csv', 'wb') as f:
    writer = csv.writer(f)
    data = [["Name", "Score"],
            [name,score]]
    writer.writerows(data)

Content of some.csv:

Name,Score
X,Y

Note this is assuming Python 2. If you are actually on Python 3, and are writing non-ASCII characters, the open has different parameters.

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

Upvotes: 2

Josh B.
Josh B.

Reputation: 432

The reason that you are getting that error is because you are trying to encode a list, not a string.

I made a working code that wrote "Name" in a .csv file with this script.

import csv
name = "X"
score = "Y"
with open('some.csv', 'wb') as f:
    writer = csv.writer(f)
    data = [["Name", "Score"],
            [name,score]]
    f.write(data[0][0].encode('utf-8'))  #<-- Change made here
    #Removed line here

On the line that I changed, I added an extra [0]. You data list is nested, which means that there is more than one list inside of it.

If you want to get the "Name" string, you need to reference data[0][0]. This gets the first element in the outer list, with is ["Name", "Score"]. The next [0] gets the first element is that list, which is "Name".

I got rid of the line with writer.writerows(data). It was throwing me an error and I had no idea what it was supposed to do.

Upvotes: 0

Related Questions