gpt4 book ai didi

python - python中的文件路径

转载 作者:太空狗 更新时间:2023-10-30 01:59:07 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com