简体   繁体   中英

python 3 csv file - attribute error

I am trying to read in the following csv file:

https://github.com/eljefe6a/nfldata/blob/master/stadiums.csv

I copied and pasted the contents it into excel and save it as a csv file because it is in a unix format.

and I get the following attribute error message

Any help appreciated. Thank you.

import sys
import csv
with open('stadium.csv', newline='') as csvfile:
      readCSV = csv.reader(csvfile,delimiter=',')
      for line in readCSV:
          line = line.strip()
          unpacked = line.split(",")
          stadium, capacity, expanded, location, surface, turf, team, opened, weather, roof, elevation = line.split(",")
          results = [turf, "1"]
          print("\t".join(results)) 

Error:

Traceback (most recent call last):
  File "C:/Python34/mapper.py", line 31, in <module>
    line = line.strip()
AttributeError: 'list' object has no attribute 'strip'

When you call .strip() on line it doesn't work because line is a list type object. Strip is method that only applies to strings. If I'm correct about what you're trying to do the correct way to unpack the variables would be:

stadium, capacity, expanded, location, surface, turf, team, opened, weather, roof, elevation = line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7], line[8], line[9], line[10]

The above works because you put the location of the value in the list (line) within the brackets and unpack the values into their respective variables. Then call you can do:

stadium.split()

for example.

When you are using csv module, with delimiter as ',' and when you do -

for line in readCSV:

line is actually each row in the csv, and the row would be a list of all elements in that row, delimited by ',' . You actually do not need to strip or split them again.

You can try -

import sys
import csv
with open('stadium.csv', newline='') as csvfile:
    readCSV = csv.reader(csvfile,delimiter=',')
    for line in readCSV:
        stadium, capacity, expanded, location, surface, turf, team,opened, weather, roof, elevation = line
        results = [turf, "1"]
        print("\t".join(results)) 

Please do make sure that the elements you do unpacking are there in the csv.

The CSV reader already separates all the fields for you. That is, your line variable is already a list, not a string, so there's nothing to strip and nothing to split. Use line the way you intended to use unpacked .

That's why you're using the csv package in the first place, remember.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM