目錄結構
python常用模塊(文件夾)
python_os(文件夾)
os_獲取絕對路徑.py
### 方法一
os_獲取絕對路徑.py
#coding:utf8
import os
#獲取當前目錄絕對路徑
dir_path = os.path.dirname(os.path.abspath(__file__))
print('當前目錄絕對路徑:',dir_path)
#獲取上級目錄絕對路徑
dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print('上級目錄絕對路徑:',dir_path)
運行結果
當前目錄絕對路徑: D:\python常用模塊\python_os
上級目錄絕對路徑: D:\python常用模塊
簡化代碼
# coding :utf8
from os.path import *
# 獲取當前目錄絕對路徑
dir_path = dirname(abspath(__file__))
print('當前目錄絕對路徑:', dir_path)
# 獲取上級目錄絕對路徑
dir_path = dirname(dirname(abspath(__file__)))
print('上級目錄絕對路徑:', dir_path)h)
運行結果
當前目錄絕對路徑: 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常用模塊