我按照書中的示例並收到錯誤。我有兩個文件。一個名爲nobel_winners.csv,另一個名爲test.py,我試圖從test.py中打開nobel_winners.csv。使用Python打開.csv文件NameError
nobel_winners.csv的內容是:
nobel_winners = [
{'category': 'Physics',
'name': 'Albert Einstein',
'nationality': 'Swiss',
'sex': 'male',
'year': 1921},
{'category': 'Physics',
'name': 'Paul Dirac',
'nationality': 'British',
'sex': 'male',
'year': 1933},
{'category': 'Chemistry',
'name': 'Marie Curie',
'nationality': 'Polish',
'sex': 'female',
'year': 1911}
]
從我test.py,我使用f = open('nobel_winners.csv', 'w')
然後cols = nobel_winners[0].keys()
。然後程序拋出:
NameError: name 'nobel_winners' is not defined.
這裏會出現什麼錯誤?
爲什麼這個文件命名爲.csv?另外,它似乎是該文件是一個有效的Python字典列表?你能控制文件的名稱嗎?因爲那樣你就可以將它作爲一個.py文件,只需將其導入並直接用作有效的Python數據結構。 – idjaw
當你說'cols = nobel_winners [0] .keys()''nobel_winners'分配了什麼?您可能沒有定義該錯誤發生的變量。 – shaktimaan
您的'nobel_winners.csv'不是CSV文件,而是普通的Python文件。將其重命名爲'nobel_winners.py'並從nobel_winners import *'導入' – furas