8

我正在尝试加载 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 我哪里出错了?

4

3 回答 3

14

I prefer to point pathes starting from file directory

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

this allows not to care about working directory changes. And also this allows to run script from any directory using it's full path.

python script/inner/script.py

or

python script.py
于 2013-09-23T08:26:29.787 回答
1

我会使用os.path.join方法来形成从当前目录开始的完整路径。

就像是:

json_filepath = os.path.join('.', 'folder1', 'sub1', 'sub2', 'sub3', 'file.json')
于 2013-09-23T08:15:46.167 回答
0

与往常一样,初始斜线表示路径从根开始。省略初始斜杠以指示它是相对路径。

于 2013-09-23T07:51:25.450 回答