我正在尝试加载 json 文件,但它给我一个错误提示 No such file or directory:
with open ('folder1/sub1/sub2/sub2/sub3/file.json') as f:
data = json.load(f)
print data
上述文件 main.py 保存在 folder1
之外。所有这些都保存在项目文件夹下。
所以,目录结构是Project/folder1/sub1/sub2/sub2/sub3/file.json 我哪里错了?
最佳答案
我更喜欢从文件目录开始指向路径
import os
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, 'relative/path/to/file.json')
with open(file_path, 'r') as fi:
pass
这允许不关心工作目录的变化。这也允许使用它的完整路径从任何目录运行脚本。
python script/inner/script.py
或
python script.py
关于python - python中的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18954198/