IOError: [Errno 2] No such file or directory的解決方法
阿新 • • 發佈:2019-01-23
利用python讀取檔案或者圖片的時候,可能會出現讀寫檔案出錯。報錯的資訊如下:
IOError: [Errno 2] No such file or directory
檔名readXML.py,有一個配置檔案a.txt放在同一目錄下。程式碼如下:
import codecs
def readXML():
path = *a.txt*
fopen = codecs.open(path,*r*,encoding=*utf8*)
print str(fopen.read())
return 1
報錯資訊如下:
Traceback (most recent call last):
File "<input>" , line 1, in <module>
File "D:\Source_Codes_Pra\test\CDA_URL_\readXML.py", line 4, in readXML
fopen = codecs.open(path,*r*,encoding=*utf8*)
File "C:\Python27\lib\codecs.py", line 881, in open
file = __builtin__.open(filename, mode, buffering)
IOError: [Errno 2] No such file or directory: *a.txt*
那麼在程式碼沒有任何問題的情況之下,這是什麼原因呢?筆者在參考很多解決方法之後,發現了這是由於讀取的檔案路徑不對而找不到檔案的問題。
那麼我們可以用以下的方式加在程式碼之中,檢視當前的工作路徑:
import os
print os.getcwd() #打印出當前工作路徑
也可以修改當前的工作路徑,方法如下:
os.chdir('the dir which include the file a.txt') #修改當前工作目錄
這樣解決方法是
1、可以將要讀取的檔案與圖片放到當前的路徑之下;
2、也可以將工作路徑修改成藥讀取的檔案與圖片的路徑中;