首頁 >後端開發 >Python教學 >如何存取 Python 套件內的靜態檔案?

如何存取 Python 套件內的靜態檔案?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-12-05 09:10:13796瀏覽

How Can I Access Static Files Inside a Python Package?

如何存取Python 套件內的靜態檔案

要讀取位於Python 套件內的文件,有以下幾種方法可用的方法。一個推薦的方法是利用 Python 3.7 中引入的 importlib.resources 模組。

from importlib import resources
from . import templates

inp_file = resources.files(templates) / 'temp_file'
# open the file using the file-like stream context manager
with inp_file.open("rt") as f:
    template = f.read()

與舊版 pkg_resources 模組相比,此方法具有多種優勢。它性能更高,更安全,不需要路徑操作,並且僅依賴標準庫。

對於那些使用 3.7 之前的 Python 版本的用戶,或者為了向後相容,可以向後移植 importlib_resources 庫。

try:
    from importlib import resources
except ImportError:
    import importlib_resources

from . import templates

inp_file = resources.files(templates) / 'temp_file'
try:
    with inp_file.open("rb") as f:  # or "rt" as text file with universal newlines
        template = f.read()
except AttributeError:
    # Python < PY3.9, fall back to method deprecated in PY3.11.
    template = resources.read_text(templates, 'temp_file')

在此上下文中,resources.files() 函數傳回 PathLike 對象,該物件表示目標檔案的路徑。 Resource_name 參數現在表示套件內的檔案名,沒有任何路徑分隔符號。若要存取目前模組中的文件,請指定 __package__ 作為套件參數(例如,resources.read_text(__package__, 'temp_file'))。

以上是如何存取 Python 套件內的靜態檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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