python打印當前文件的絕對路徑并解決打印為空的問題
python打印當前文件的絕對路徑并解決打印為空
獲取當前文件所在路徑主要使用os.path.dirname(os.path.abspath(__file__))
:
import os file_path = os.path.dirname(os.path.abspath(__file__)) print(file_path)
不能使用下面代碼,在有些情況下路徑會是空
os.path.dirname(__file__)
示例:得到相對位置的文件路徑
上級文件夾下的文件,比如config.yaml
文件的路徑可以表示為:os.path.dirname(os.path.abspath(__file__)) + "/../conf/config.yaml"
|_ conf |_ config.yaml |_src |_代碼 # 當前位置
補充:python中對文件路徑的獲取
1、獲取當前文件的絕對路徑
import os cur_path = os.path.abspath(__file__) print(cur_path)
輸出:E:\python\project\test\path_test.py
2、獲取當前文件的所在目錄
import os cur_dir = os.path.dirname(os.path.abspath(__file__)) # 上級目錄 print(cur_dir)
輸出:E:\python\project\test
3、獲取當前文件所在目錄的上一級目錄
import os cur_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 上級目錄 print(cur_dir)
輸出:E:\python\project
4、獲取指定文件的路徑(例如想獲得project文件夾下的test.txt文件路徑)
import os # 法一 cur_dir1 = os.path.dirname(os.path.abspath(__file__)) path1 = os.path.join(os.path.abspath(cur_dir + os.path.sep + ".."), "test.txt") # 法二 cur_dir2 = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) path2 = os.path.join(os.path.dirname(cur_dir), "test.txt") print(path1) print(path2)
輸出:
E:\python\project\test.txt
E:\python\project\test.txt
注意:
只有當在腳本中執(zhí)行的時候,os.path.abspath(file)才會起作用,因為該命令是獲取的當前執(zhí)行腳本的完整路徑,如果在交互模式或者terminate 終端中運行會報沒有__file__這個錯誤。
到此這篇關(guān)于python打印當前文件的絕對路徑,并解決打印為空的文章就介紹到這了,更多相關(guān)python打印當前文件的絕對路徑內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深度學(xué)習的MNIST手寫數(shù)字數(shù)據(jù)集識別方式(準確率99%,附代碼)
這篇文章主要介紹了深度學(xué)習的MNIST手寫數(shù)字數(shù)據(jù)集識別方式(準確率99%,附代碼),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06