Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

Open .csv file with Python throws NameError

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...