简体   繁体   English

使用 python 将 Json 文件保存到指定目录

[英]saving the Json file into a specified directory using python

I have a python file demo.py, I have created a JSON file using the demo.py file.我有一个 python 文件 demo.py,我使用 demo.py 文件创建了一个 JSON 文件。

    def write_json(new_data, filename='Report.JSON'):
        with open(filename, 'w') as f:
            json_string=json.dumps(new_data)
            f.write(json_string)

This is creating a JSON file in the same directory in which the demo.py is present.这是在 demo.py 所在的同一目录中创建 JSON 文件。 If I want to save this report.json file into some other directory, how can I do that如果我想将此 report.json 文件保存到其他目录中,我该怎么做

Thanks in advance.提前致谢。

The problem here is that filename in with statement is only the filename and for this reason the file is created in the same directory of the python file.这里的问题是 with 语句中的文件名只是文件名,因此该文件是在 python 文件的同一目录中创建的。

If you want to have a specific path for the new file, you have to specify the full path for the filename parameter.如果您想为新文件指定一个特定路径,则必须为 filename 参数指定完整路径。
In this way in这样在

 with open(filename, "w") as f:

the filename variable will contains the whole path and the json file will be saved in the correct directory文件名变量将包含整个路径,并且 json 文件将保存在正确的目录中

Keep in mind that you can also hardcode the path using something like this:请记住,您还可以使用以下方式对路径进行硬编码:

import os
def write_json(new_data, filename="Report.JSON"):
    desired_dir = "<custom_dir_here>"
    full_path = os.path.join(desired_dir, filename)
    with open(full_path, 'w') as f:
        json_string=json.dumps(new_data)
        f.write(json_string)

You can use您可以使用

import os
os.chdir("C:/MyPath")

To change working directory you're in.要更改您所在的工作目录。

Will make your life easier if You are going to work with multiple files如果您要处理多个文件,将使您的生活更轻松

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

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