Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm following an example in a book and receiving an error. I have two files. One is named nobel_winners.csv and the other test.py I am trying to open nobel_winners.csv from test.py.

The contents of nobel_winners.csv is:

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}
]

from my test.py, I'm using f = open('nobel_winners.csv', 'w') then cols = nobel_winners[0].keys(). The program then throws:

NameError: name 'nobel_winners' is not defined.

What is going awry here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

I think that's because the variable 'nobel_winners' is not defined before you call it.

I'm not aware with your code but if you are reading from csv, the code below works for me. This my not be the best way though. I did it with some guidance from a question posted here in this site.

def read_from_csv(filename,nrows,ncols):
csv_data = np.zeros((nrows,ncols))

with open(filename,'rb') as csvfile:
  read_csv = csv.reader(csvfile)
  i=0
  for row in read_csv:
      csv_data[i] = np.array(row)
      csv_data[i] = csv_data[i].astype(np.float)
      i += 1
csvfile.close()
return csv_data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...