我的包结构如下:
my_pkg:
在 foo.py 模块中,我有类似的内容:
import json
def loadFromJSON(fileName):
with open(fileName,'r') as f:
xs = json.load(f)
return xs
bar = loadFromJSON('bar.json')
问题是当我尝试从 my_pkg :
导入内容时python
>>> from my_pkg import *
>>> ..../my_pkg/proj2/foo.py in loadFromJSON(fileName)
>>> ---> with open(fileName,'r') as f:
>>> xs = json.load(f)
>>> return xs
>>> FileNotFoundError: [Errno 2] No such file or directory: 'bar.json'
但如果我这样做:
>>> cwd
>>> '.../my_pkg/proj2/`
>>> from foo import bar
>>> bar
有效。有人可以解释一下这里发生了什么吗?
答案 0 :(得分:1)
(为了完整性,我将评论转移到答案)
我认为你应该为你使用完整的路径" bar.json"文件。
答案 1 :(得分:0)
就像您说的那样,重点是“ cwd”: 您可以添加“ cwd”,然后导入模块:
"body-parser": "^1.18.3",
"express": "^4.16.3",
"express-promise-router": "^3.0.3",
"mongoose": "^5.3.1",
然后做:
import sys
sys.path.append('your cwd here')