简体   繁体   中英

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.

    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. If I want to save this report.json file into some other directory, how can I do that

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.

If you want to have a specific path for the new file, you have to specify the full path for the filename parameter.
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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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