您的位置:首頁技術文章
文章詳情頁

Python 解決相對路徑問題:"No such file or directory"

瀏覽:114日期:2022-07-22 17:15:54

如果你取相對路徑不是在主文件里,可能就會有相對路徑問題:'No such file or directory'。

因為 python 的相對路徑,相對的都是主文件。

如下目錄結構:

| -- main.py | -- conf.py | -- start.png| -- config.txt

main.py 是主文件。

conf.py 里引用 config.txt 用相對路徑。

如果用 . 或 … 相對的是 main.py,所以用 './config.txt',相對于 main.py 是同一個目錄下。

.指當前文件所在的文件夾,… 指當前文件的上一級目錄。

補充知識:解決python模塊調用時代碼中使用相對路徑訪問的文件,提示文件不存在的問題

問題分析:

在編碼過程中使用相對路徑使代碼的穩定性更好,即使項目目錄發生變更,只要文件相對路徑不變,代碼依然可以穩定運行。但是在python代碼中使用相對路徑時會存在以下問題,示例代碼結構如下:

Python 解決相對路徑問題:"No such file or directory"

其中test包中包含兩個文件first.py和user_info.txt,first.py代碼中只有一個函數read_file,用于讀取user_info.txt文件第一行的內容,并打印結果,讀取文件使用相對路徑,代碼如下:

import osprint('當前路徑 -> %s' %os.getcwd())def read_file() : with open('user_info.txt' , encoding = ’utf-8’) as f_obj : content = f_obj.readline() print('文件內容 -> %s' %content) if __name__ == ’__main__’ : read_file()

first.py程序代碼執行結果如下:

當前路徑 -> E:程序python代碼PythonDataAnalysisDemotest

文件內容 -> hello python !!!

與test在同一目錄下存在一個second.py文件,在這個文件中調用first.py文件中的read_file方法讀取user_info.txt文件,代碼如下:

from test import first

first.read_file()

second.py程序執行結果如下:

當前路徑 -> E:程序python代碼PythonDataAnalysisDemo

File 'E:/程序/python代碼/PythonDataAnalysis/Demo/second.py', line 8, in <module>

first.read_file()

File 'E:程序python代碼PythonDataAnalysisDemotestfirst.py', line 10, in read_file

with open('user_info.txt' , encoding = ’utf-8’) as f_obj :

FileNotFoundError: [Errno 2] No such fileor directory: ’user_info.txt’

以上信息提示user_info.txt 文件不存在,查看os.getcwd() 函數輸出的當前路徑會發現,當前路徑是 XXX/Demo,而不是上一次單獨執行first.py 文件時的 XXX/Demo/test了,所以程序報錯文件不存在的根本原因是因為當前路徑變了,導致代碼中的由相對路徑構成的絕對路徑發生了變化。

解決方法:

對于這種問題,只需要在使用相對路徑進行文件訪問的模塊中加入以下代碼即可(加粗內容),修改后的first.py代碼如下:

import osprint('當前路徑 -> %s' %os.getcwd())current_path = os.path.dirname(__file__)def read_file() : with open(current_path + '/user_info.txt' , encoding = ’utf-8’) as f_obj : content = f_obj.readline() print('文件內容 -> %s' %content) if __name__ == ’__main__’ : read_file()

first.py 程序執行結果如下:

當前路徑 -> E:程序python代碼PythonDataAnalysisDemotest

current_path -> E:/程序/python代碼/PythonDataAnalysis/Demo/test

文件內容 -> hello python !!!

second.py代碼不變,second.py代碼執行結果如下:

當前路徑 -> E:程序python代碼PythonDataAnalysisDemo

current_path -> E:程序python代碼PythonDataAnalysisDemotest

文件內容 -> hello python !!!

由以上執行結果可以發現,雖然first.py和second.py代碼執行時os.getcwd()函數的輸出結果還是不一致,但是current_path = os.path.dirname(__file__)

代碼得到的current_path路徑是相同的,current_path就是first.py文件所處的路徑,然后再由current_path 和user_info.txt 組成的文件絕對路徑則是固定的,這樣就可以確保在進行模塊導入時,模塊中使用相對路徑進行訪問的文件不會出錯。

以上這篇Python 解決相對路徑問題:'No such file or directory'就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
国产综合久久一区二区三区