共計 631 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用 os.path
模塊來獲取相對路徑。具體步驟如下:
-
導入
os.path
模塊:import os.path
-
使用
os.path.abspath()
函數獲取當前文件的絕對路徑:current_path = os.path.abspath(__file__)
-
使用
os.path.dirname()
函數獲取當前文件的目錄路徑:current_dir = os.path.dirname(current_path)
-
使用
os.path.join()
函數拼接相對路徑:relative_path = os.path.join(current_dir, '相對路徑')
下面是一個完整的示例代碼:
import os.path
# 獲取當前文件的絕對路徑
current_path = os.path.abspath(__file__)
# 獲取當前文件的目錄路徑
current_dir = os.path.dirname(current_path)
# 拼接相對路徑
relative_path = os.path.join(current_dir, ' 相對路徑 ')
print(relative_path)
注意:在上述代碼中,__file__
表示當前文件的路徑。os.path.abspath()
函數將其轉換為絕對路徑,os.path.dirname()
函數獲取其所在的目錄路徑。最后使用 os.path.join()
函數拼接相對路徑,得到最終的相對路徑。
丸趣 TV 網 – 提供最優質的資源集合!
正文完