python - python中的文件路径

标签 python json file

我正在尝试加载 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/

相关文章:

python - 找到固定长度数字的所有可能排列以达到给定的总和

python - 函数 string.lstrip() 在 python 中返回空白字符串

javascript - Axios 将 index.html 内容返回给前端(React.js)

javascript - 将 JSON 数据链接到 d3 中的 g 元素

java - 使用 FileReader 时解决 IOException、FileNotFoundException

python - 在 python 中,如何输入提示不是 str 或 bytes 而是序列的输入?

javascript - 在 NodeJS 中将 K,V 对分配给 JSON 对象

php - 获取 JSON 以打印空数组。

file - 用 bash 读取文本文件的前 8 个字符

Java/Android : Byte to file not saving?