2014-11-02 209 views
0

我對python完全陌生。 我想讀,我已經創建了一個文件,但提示以下錯誤:Python:無法打開和讀取文件

File "C:/Python25/Test scripts/Readfile.py", line 1, in <module> 
    filename = open('C:\Python25\Test scripts\newfile','r') 
IOError: [Errno 2] No such file or directory: 'C:\\Python25\\Test scripts\newfile 

我的代碼:

filename = open('C:\Python25\Test scripts\newfile','r') 
print filename.read() 

我也試過

filename = open('C:\\Python25\\Test scripts\\newfile','r') 
print filename.read() 

但同樣的錯誤我得到。

+5

'newfile'是否有擴展名(如'.txt')? – 2014-11-02 21:25:02

+0

我會添加.txt擴展名,另外我會刪除Test與腳本之間的空間,並用下劃線替換它(即重命名該目錄,如果它確實有空格)。 – 2014-11-02 21:43:41

回答

1

嘗試:

fpath = r'C:\Python25\Test scripts\newfile' 
if not os.path.exists(fpath): 
    print 'File does not exist' 
    return 

with open(fpath, 'r') as src: 
    src.read() 

首先你驗證文件,它的存在。 然後你打開它。隨着包裝更有用,它會在你閱讀完之後關閉你的文件。所以你不會卡住許多開放的描述符。

0

我想你可能有這個問題,因爲你沒有包括完整的文件名。

你應該嘗試:

filename = open('C:\Python25\Test scripts\newfile.txt','r') 
print filename.read() 

*此外,如果你正在運行在相同的位置,您正在打開目標文件這條巨蟒文件,你並不需要給完整的目錄,你可以只是打電話:

filename = open(newfile.txt