在python目录外创建一个文件

Pyt*_*ast 5 python file

我想在python中创建当前工作目录之外的文件.这是我的目录结构.

|--myproject
|   |-- gui
|   |   |-- modules
|   |   |   |-- energy
|   |   |   |   |-- configuration
|   |   |   |   |   |-- working_file.py
|   |-- service
|   |   |-- constants
|   |   |   |-- global_variables.json    
Run Code Online (Sandbox Code Playgroud)

我目前正在工作/myproject/gui/energy/configuration/working_file.py,我想在/myproject/service/constantsnamed 下创建一个文件global_variables.json

我试过了

with open("../../../../../service/constants/global_variables.json", 'w') as file_handler:
        content = json.load(file_handler)
Run Code Online (Sandbox Code Playgroud)

svv*_*vac 6

相对路径从当前工作目录解析,而不是从脚本所在的目录解析.如果您尝试创建的文件需要位于特定目录中,请使用绝对路径(例如/absolute/path/to/myproject/service/constants/global_variables.json).

如果您无法知道此绝对路径,请参阅此SO问题