1
2
3
4
5
6
|
#當前文件的路徑
pwd
=
os.getcwd()
#當前文件的父路徑
father_path
=
os.path.abspath(os.path.dirname(pwd)
+
os.path.sep
+
"."
)
#當前文件的前兩級目錄
grader_father
=
os.path.abspath(os.path.dirname(pwd)
+
os.path.sep
+
".."
)
|
第一種方法:
os.path.abspath(__file__)
假設app.py中想讀取config.ini文件的內容,首先app.py需要知道config.ini的文件路徑,從目錄結構上可以看出,config.ini與app.py的父目錄同級,也就是獲取到app.py父目錄(bin文件夾的路徑)的父目錄(config文件夾路徑)的絕對路徑再拼上config.ini文件名就能獲取到config.ini文件
首先,在app.py中測試一下:
import os def load_file(): # 獲取當前文件路徑 current_path = os.path.abspath(__file__) # 獲取當前文件的父目錄 father_path = os.path.abspath(os.path.dirname(current_path) + os.path.sep + ".") # config.ini文件路徑,獲取當前目錄的父目錄的父目錄與congig.ini拼接 config_file_path=os.path.join(os.path.abspath(os.path.dirname(current_path) + os.path.sep + ".."),'config.ini') print('當前目錄:' + current_path) print('當前父目錄:' + father_path) print('config.ini路徑:' + config_file_path) load_file()
輸出結果:
當前目錄:/Users/shanml/Documents/python/config/bin/app.py
當前父目錄:/Users/shanml/Documents/python/config/bin
config.ini路徑:/Users/shanml/Documents/python/config/config.ini
從結果中可以看到一切都正常,沒有什么問題,假如現在需要從main.py中執行app.py的load_file()方法呢?
來測試一下:
main.py from bin.app import load_file if __name__=='__main__': load_file()
輸出結果,路徑同樣沒問題:
當前目錄:/Users/shanml/Documents/python/config/main.py
當前父目錄:/Users/shanml/Documents/python/config
config.ini路徑:/Users/shanml/Documents/python/config.ini
參考:https://www.cnblogs.com/yajing-zh/p/6807968.html
第二種方法:
使用inspect
app.py:
import os,inspect def load_file(): # 獲取當前文件路徑 current_path=inspect.getfile(inspect.currentframe()) # 獲取當前文件所在目錄,相當於當前文件的父目錄 dir_name=os.path.dirname(current_path) # 轉換為絕對路徑 file_abs_path=os.path.abspath(dir_name) # 划分目錄,比如a/b/c划分后變為a/b和c list_path=os.path.split(file_abs_path) print('list_path:' + str(list_path)) # 配置文件路徑 config_file_path=os.path.join(list_path[0],'config.ini') print('當前目錄:' + current_path) print('config.ini文件路徑:' + config_file_path)
在app.py中執行load_file()方法:
list_path:('/Users/shanml/Documents/python/config', 'bin')
當前目錄:/Users/shanml/Documents/python/config/bin/app.py
config.ini文件路徑:/Users/shanml/Documents/python/config/config.ini
在mian.py中執行load_file方法:
list_path:('/Users/shanml/Documents/python/config', 'bin')
當前目錄:/Users/shanml/Documents/python/config/bin/app.py
config.ini文件路徑:/Users/shanml/Documents/python/config/config.ini
參考:https://xnow.me/programs/python.html
---------------------
作者:S_H-A_N
來源:CSDN
原文:https://blog.csdn.net/lom9357bye/article/details/79285170
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!