[英]How to get the absolute path of the imported python file
我有以下代碼結構:
config_dir
config.py
main.py
在config.py中有一個方法如下:
def get_path():
# TODO
return "the absolute path of config.py, not the path of the main.py that import this config module"
在 main.py 中,我導入配置模塊並調用配置的方法 get_path
from config_dir import config
print(config.get_path())
我想打印 config.py 的絕對路徑,而不是導入此配置模塊的 main.py 的路徑
想請教一下這個代碼怎么寫,謝謝!
您可以使用文件獲取導入模塊的絕對路徑。 例如:
from config_dir import config
print(config.__file__)
>>> import datetime
>>> datetime.__file__
'/usr/local/Cellar/python@2/2.7.17/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/datetime.so'
>>>
你可以使用這個:
import os
def get_path():
return os.path.abspath(__file__)
試試下面的代碼:
import os
os.path.abspath(config)
在config.py
中添加如下代碼
import os
def get_path():
return os.path.abspath(__file__)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.