2016年5月15日 星期日

[python] 使用 pkg_resources 模組存取 package 裡面的檔案

import pkg_resources

strPkgFilePath = pkg_resources.resource_filename("package_name", "resource_file")

當資源存放在 package (含有 __init__.py 的資料夾)裡面時,
一但經過封裝上傳  pip install  之後,檔案路徑會與 os.path 取得的路徑不同,
os.path 是根據 "當前執行的目錄 (cwd)" 去做尋找,也就是說:

在 c:\ 下執行 會尋找 c:\package_name\resource_file
在 c:\dir\ 下執行會尋找 c:\dir\package_name\resource_file
不可能因為執行的 cwd 不同而到處搬移 resource_file 
於是會將 resource_file 存放在 package 下,pip install 後
resourc_file 會固定放在 C:\Python34\Lib\site-packages\package_name\resource_file
而要取得該位置,只要使用 pkg_resources.resource_filename 即可。

沒有留言: