Python 獲取當前文件 當前目錄 上級目錄 上上級目錄

import os

# 獲取當前目錄
print(os.getcwd())
print(os.path.abspath(os.path.dirname(__file__)))
print(os.path.abspath('.'))

# 獲取當前文件
print(os.path.abspath(__file__))

# 獲取上級目錄
print(os.path.abspath(os.path.dirname(os.getcwd())))
print(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
print(os.path.abspath(os.path.join(os.getcwd(), "..")))

# 獲取上上級目錄
print(os.path.abspath(os.path.join(os.getcwd(), "../..")))

註釋

os.getcwd()  # Return a unicode string representing the current working directory
os.path.dirname()  # Returns the directory component of a pathname
os.path.abspath()  # Return the absolute version of a path
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章