excel的CSV文件不能与程序一起使用?

时间:2014-01-17 15:55:45

标签: python

我的程序无法运行,它会返回错误...

Traceback (most recent call last):
File "C:/Python33/nasa missions apllication.py", line 16, in <module>
nasa = find_details(lookup_id)
File "C:/Python33/nasa missions apllication.py", line 4, in find_details
nasa_f= open("nasa_missions.csv")
FileNotFoundError: [Errno 2] No such file or directory: 'nasa_missions.csv'

这是我的程序......

import csv

def find_details(lookup_id):
   nasa_f= open("nasa_missions.csv")
   for each_line in nasa_f:
      z = {} 
      (z['e'], z['f'], z['g'], z['h'], z['i']) = each_line.split(",")
      if lookup_id == int(z['a']):
         nasa_f.close()
         return(z)
   nasa_f.close()
   print("This nasa space mission is not in the database")
   return({})

lookup_id = int(input("Enter the id for most succesful nasa space missions: "))   
nasa = find_details(lookup_id)

if nasa:
    print("Index:     " + nasa['e'])
    print("Mission:   " + nasa['f'])
    print("Luanch:    " + nasa['g'])
    print("Status:    " + nasa['h'])
    print("Scientific Objectives for Space:       " + nasa['i'])

出于某种原因,CSV文件无法从excel打开?

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

这与Excel或文件的格式无关; Python正试图打开该文件:

nasa_f= open("nasa_missions.csv")

但根本无法找到它。您的计算机上nasa_missions.csv存储在哪里?坦率地说,最简单的方法是将文件复制或移动到C:/Python33/

另请注意,您通常应按如下方式访问文件:

with open("nasa_missions.csv") as nasa_f:
    # use the file here
# file is automatically closed when you leave the with block

答案 1 :(得分:1)

这意味着python无法找到文件的路径。

您可以使用os.chdir(dir)切换到“nasa_missions.csv”文件的目录。