[英]python 3 csv file - attribute error
我正在嘗試閱讀以下csv文件:
https://github.com/eljefe6a/nfldata/blob/master/stadiums.csv
我將其內容復制並粘貼到excel中,因為它是unix格式,所以另存為csv文件。
我收到以下屬性錯誤消息
任何幫助表示贊賞。 謝謝。
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'
當您在線調用.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()
例如。
當您使用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中。
CSV閱讀器已經為您分隔了所有字段。 也就是說,您的line
變量已經是一個列表,而不是字符串,因此沒有要剝離的內容,也沒有要拆分的內容。 使用line
你打算使用的方式unpacked
。
請記住,這就是為什么首先使用csv
包的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.