2015-07-12 81 views
0

我想在下面的csv文件閱讀:蟒蛇3 CSV文件 - 屬性錯誤

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

我複製並粘貼的內容就到Excel並保存爲一個CSV文件,因爲它是在一個unix格式。

和我得到以下屬性錯誤信息

任何幫助表示讚賞。謝謝。

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)) 

錯誤:

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

我不知道爲什麼你再次分裂'line.split(「,」)' –

回答

0

當您使用csv模塊,用分隔符爲','當你這樣做 -

for line in readCSV: 

線實際上是在CSV每一行,以及行將是該行中所有元素的列表,由','分隔。你實際上不需要去除或再次分割它們。

你可以試試 -

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)) 

請你確保你拆包的元素存在於CSV。

+0

謝謝。我只是在元素中添加了它們,並且它們是第一個字母大寫的列名。文件「C:/Python34/mapper.py」,第30行,在 球場,容量,擴展,位置,表面,草皮,團隊,已打開,天氣,屋頂,海拔 NameError:名稱'Stadium'沒有定義 – user4745212

+0

我忘了把它們用引號括起來,所以現在就起作用了。謝謝 – user4745212

0

CSV閱讀器已經爲您分隔了所有字段。也就是說,你的line變量已經是一個列表,而不是一個字符串,所以沒有東西可以剝離,也沒有東西可以分割。使用line您打算使用的方式unpacked

這就是爲什麼你首先使用csv包,請記住。

1

當您在線調用.strip()時,它不起作用,因爲line是一個列表類型對象。 Strip是僅適用於字符串的方法。如果我對你正在試圖做的解包的正確方法是什麼正確的變量是:

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] 

上述工作,因爲你把值的位置列表(線)括號內並將這些值解壓到它們各自的變量中。 然後你可以這樣做:

stadium.split() 

例如。