1. 程式人生 > 程式設計 >Python 解決相對路徑問題:"No such file or directory"

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

如果你取相對路徑不是在主檔案裡,可能就會有相對路徑問題:"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 os
print("當前路徑 -> %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程式碼\PythonDataAnalysis\Demo\test

檔案內容 -> hello python !!!

與test在同一目錄下存在一個second.py檔案,在這個檔案中呼叫first.py檔案中的read_file方法讀取user_info.txt檔案,程式碼如下:

from test import first

first.read_file()

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

當前路徑 -> E:\程式\python程式碼\PythonDataAnalysis\Demo

File "E:/程式/python程式碼/PythonDataAnalysis/Demo/second.py",line 8,in <module>

first.read_file()

File "E:\程式\python程式碼\PythonDataAnalysis\Demo\test\first.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 os
print("當前路徑 -> %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程式碼\PythonDataAnalysis\Demo\test

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

檔案內容 -> hello python !!!

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

當前路徑 -> E:\程式\python程式碼\PythonDataAnalysis\Demo

current_path -> E:\程式\python程式碼\PythonDataAnalysis\Demo\test

檔案內容 -> 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"就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。