天天看點

python - OS 擷取絕對路徑

目錄結構

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常用子產品