如何獲得當前 Python 指令碼檔案的資料夾路徑
我們在 Python 3 基礎教程中介紹了檔案和資料夾操作,在本貼士中我們來介紹下如何得到當前 Python 指令碼檔案的相對和絕對路徑。
獲得 Python 工作目錄
os.getcwd()
函式返回了當前 Python 工作目錄,如果你是在 Python IDLE
中執行該命令的話,返回結果就是 Python IDLE
的路徑。
Python 中獲得該執行檔案的目錄
指令碼檔案的路徑可以在全域性名稱空間中找到,它的變數名稱是 __file__
。該變數是相對於 Python 工作目錄的相對路徑。
我們用示例程式碼來實際操作下剛才介紹的知識。
import os
wd = os.getcwd()
print("working directory is ", wd)
filePath = __file__
print("This script file path is ", filePath)
absFilePath = os.path.abspath(__file__)
print("This script absolute path is ", absFilePath)
path, filename = os.path.split(absFilePath)
print("Script file path is {}, filename is {}".format(path, filename))
absFilePath = os.path.abspath(__file__)
os.path.abspath(__file__)
函式的結果是給定相對路徑的絕對路徑。
path, filename = os.path.split(absFilePath)
os.path.split()
函式返回了兩個結果,一個是輸入檔名的純路徑名,另一個是純檔名。
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn