python中獲取檔案路徑的幾種方式
阿新 • • 發佈:2020-07-08
# 如果執行檔案為E:\aa\bb\aa.py
1.獲取當前路徑
current_path11 = os.path.abspath(__file__)
current_path12 = os.path.realpath(__file__)
# 說明:以上2種方式返回結果一樣,均為E:\aa\bb\aa.py
2.獲取父路徑
pra_path11 = os.path.abspath(os.curdir)
pra_path12 = os.path.dirname(os.path.abspath(__file__))
說明:1.返回結果為E:\aa\bb
2.區別:pra_path11返回的是執行檔案所在資料夾,如果其他檔案呼叫aa.py,則返回其他檔案的父路徑。
例如檔案E:\aa\cc.py呼叫aa.py,則返回E:\aa
pra_path12返回的是aa.py檔案所在資料夾,不管誰呼叫返回均為E:\aa\bb
3.獲取父路徑的父路徑
pra_path2 = os.path.dirname(pra_path12)
返回結果為E:\aa
4.路徑連線
方式一,直接用“+”:new_path = pra_path2+ "\\report\\" + "config.ini"
方式二,用join: new_path = os.path.join(pra_path2,‘report’,'config.ini')
#新路徑E:\aa\report\config.ini
5.建立路徑
if not os.path.exists(new_path):
os.makedirs(new_path)