首頁 >後端開發 >Python教學 >如何指定 Python 腳本位置的相對路徑?

如何指定 Python 腳本位置的相對路徑?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-12-06 19:12:27851瀏覽

How to Specify Relative Paths from a Python Script's Location?

Python 中的相對路徑

在 Python 中處理檔案和目錄時,通常需要指定相對於目前工作目錄的路徑。但是,在某些情況下,您可能需要指定腳本檔案位置的相對路徑。

問題: 有沒有辦法定義腳本位置的相對路徑文件,而不是當前工作目錄?

答案:

是的,您可以使用透過以下方式取得腳本檔案所在位置的絕對路徑:

import os

# Get the directory name of the current script file
dirname = os.path.dirname(__file__)

# Construct the absolute path by joining the directory name with the relative path
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

說明:

  • __file__ 表示目前的絕對路徑腳本檔。
  • os.path.dirname(__file__) 為您提供腳本的目錄名稱檔案。
  • 透過使用 os.path.join() 將目錄名稱與相對路徑連接起來,可以獲得所需檔案的絕對路徑。

以上是如何指定 Python 腳本位置的相對路徑?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn