简体   繁体   English

如何在 python 模块中打开 json 文件

[英]How can I open a json file in modules in python

This is my project structure这是我的项目结构

我的项目结构

I am opening input.json inside user_input.get_input.py file using the following code:我正在使用以下代码在user_input.get_input.py文件中打开input.json

open('..\\data\\input.json', 'w')

When I run get_input.py file, it works perfectly.当我运行get_input.py文件时,它运行良好。 But when I run run.py file it shows me this error:但是当我运行run.py文件时,它显示了这个错误:

FileNotFoundError: [Errno 2] No such file or directory: '..\\data\\input.json'

I tried using full path too, but no success!我也尝试使用完整路径,但没有成功!

That's because the working directory of the main script you start is the working directory for the ones that you import as well.这是因为您启动的主脚本的工作目录也是您导入的主脚本的工作目录。 You can either set the working directory to be user_input in the run configuration in PyCharm, or change the path to data\\input.json when running from run.py .您可以在 PyCharm 的运行配置中将工作目录设置为user_input ,或者从run.py运行时将路径更改为data\\input.json input.json。

If you want the relative path independent of working directory in get_input.py , try this:如果你想要独立于get_input.py中工作目录的相对路径,试试这个:

from pathlib import Path

open(Path(__file__).parent.parent / 'data\\input.json', 'w')

The parent of Path(__file__) is the directory the script itself is in, and its parent is one level up. Path(__file__)parent级是脚本本身所在的目录,它的父级在上一级。 This would also work:这也行得通:

from pathlib import Path

open(Path(__file__).parent / '..\\data\\input.json', 'w')

If you don't like computing the relative path from various modules, you could also consider giving your application a global root path, accessible from its various modules, which is best depends on the exact application.如果您不喜欢计算各个模块的相对路径,您还可以考虑为您的应用程序提供一个全局根路径,可从其各个模块访问,这最好取决于具体的应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM