2015-05-17 61 views
-2

我在C:\Python27\Lib\site-packages\visual\examples中有一个名为hsp.txt的文本文件,并使用下面的代码。Python编码错误:“文件不存在”

def file(): 
    file = open('hsp.txt', 'r') 
    col = [] 
    data = file.readlines() 
    for i in range(1,len(data)-1): 
     col.append(int(float(data[i].split(',')[5]))) 
    return col 

def hist(col): 
    handspan = [] 
    for i in range(11): 
     handspan.append(0) 
    for i in (col): 
     handspan[i] += 1 
    return handspan 

col = file() 
handspan = hist(col) 
print(col) 
print(handspan) 

但是,当我运行它说,该文件不存在。

Traceback (most recent call last): 
    File "Untitled", line 17 
    col = file() 
    File "Untitled", line 2, in file 
    file = open('hsp.txt', 'r') 
IOError: [Errno 2] No such file or directory: 'hsp.txt' 

我该如何解决这个问题? 另外我如何输出均值和方差?

+1

在“os.getcwd()”中输入。它返回什么? – Zizouz212

+1

@MartijnPieters你是一个在这些可怕的问题上花费这么多时间的圣人。 – dbliss

+0

@Jeffrey当你完成这个工作时,你应该真的关闭这个文件 - 或者用'with'代码块打开这个文件。 – dbliss

回答

1

当您指定只以下行

file = open('hsp.txt', 'r') 

它试图用你的当前目录,这是在以往任何时候你推出蟒蛇。因此,如果您从命令提示符处于C:\ temp并执行python test.py,则会在C:\ temp \ hsp.txt中查找您的hsp.txt。当您不试图从当前目录加载文件时,应指定完整路径。

file = open(r'C:\Python27\Lib\site-packages\visual\examples\hsp.txt') 
2

你有没有想过你的路径导致?您需要提供完整的路径到文件。

opened_file = open("C:/Python27/Lib/site-packages/visual/examples/hsp.txt") 

一对夫妇的其他东西:

  • 不要使用file作为变量名。系统已经使用该名称。

使用with声明。这被认为是更好的做法。

with open("C:/Python27/Lib/site-packages/visual/examples/hsp.txt"): 
    # do something 

with块结束时,文件将自动关闭。在您的代码中,该文件保持打开状态,直到使用.close()方法关闭file函数(因此保存)。