1

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.

2
  • I would believe you specify a full path for the filename variable. Commented May 20, 2021 at 9:34
  • You can use like with open(f'{target_path}{filename}', 'w') as f: Commented May 20, 2021 at 9:36

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.