2015-05-17 60 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函數(因此保存)。