我从以下 python 项目中遇到了这个问题:
MyPackage
├──src
| ├──cust_function.py ----> class, functions
| ├──__init__.py
|
|--data --> folder where store raw or processed data
| |___init__.py
| |
|---config -> setup folder
| |-__init__.py
| |-config.json -> API parameters
|
└──main.py -> main file
所以,在 cust_function.py 我有一些类和方法,比如with open(filepath)
def get_file(filepath):
with open(filepath, 'r') as file:
....
return ....
现在问题来自 main.py,如果我发送这个请求:
from src.cust_function import get_file
filepath = "config/config.json"
get_file(filepath)
结果是 config.json 的 FileNotFoundError
我以不同的方式使用 os.path 和 sys.path 并且没有工作,
fpath = os.path.join(os.path.dirname(__file__), 'src', 'config')
sys.path.append(fpath)
我也用过
sys.path.append(project_name), and doesn't
Or I put same sys.path in __init__.py into config or src folder.
Of course, I tried directly in the same main.py and it works.
The idea is to understand how call methods and send arguments, like filepath, from main script and cust_function works fine.
Thanks.