python - OS(一)獲取絕對路徑

目錄結構

python常用模塊(文件夾)
    python_os(文件夾)
        os_獲取絕對路徑.py


方法一

os_獲取絕對路徑.py
#coding:utf8
import os

#獲取當前目錄絕對路徑
dir_path = os.path.abspath(os.path.dirname(__file__))
print('當前目錄絕對路徑:',dir_path)


#獲取上級目錄絕對路徑
dir_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
print('上級目錄絕對路徑:',dir_path)
運行結果
當前目錄絕對路徑: D:\python常用模塊\python_os
上級目錄絕對路徑: D:\python常用模塊


簡化代碼
from os.path import *
#獲取當前目錄絕對路徑
dir_path = abspath(dirname(__file__))
print('當前目錄絕對路徑:',dir_path)


#獲取上級目錄絕對路徑
dir_path = abspath(dirname(dirname(__file__)))
print('上級目錄絕對路徑:',dir_path)
運行結果
當前目錄絕對路徑: D:\python常用模塊\python_os
上級目錄絕對路徑: D:\python常用模塊




方法二

os_獲取絕對路徑.py
import os
#獲取當前目錄絕對路徑
dir_path = os.path.abspath(os.path.split(__file__)[0])
print('當前目錄絕對路徑:',dir_path)


#獲取上級目錄絕對路徑
dir_path = os.path.abspath(os.path.split(os.path.split(__file__)[0])[0])
print('上級目錄絕對路徑:',dir_path)
運行結果
當前目錄絕對路徑: D:\python常用模塊\python_os
上級目錄絕對路徑: D:\python常用模塊






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章