bluethundr
bluethundr

Reputation: 1325

Problem writing JSON to file using Python

I am trying to write a JSON file to the file system using Python. When I go to read the file there's nothing there. I think I'm doing something else wrong.

This is my code:

    today = datetime.today()
    output_dir = "../../../json/iam"
    output_file = output_dir + 'pol-aws-secrets-manager-' + user_name + today +'.json'
    policy_doc = {"blah":"blah"}
    with open(output_file, 'w+') as writer:
        json.dump(policy_doc,writer)

What am I doing wrong?

Upvotes: 0

Views: 162

Answers (2)

Irek
Irek

Reputation: 197

In addition to the response above. I tried your code and it created a file with {"blah":"blah"} without any issues.

The problem could be in the path you specified.

Upvotes: 2

Chris
Chris

Reputation: 136889

Take a look in ../../../json/ for your files.

You're building your filenames by sticking strings together, which is very error prone. In this case you've forgotten a /, so instead of getting files like

../../../json/iam/foo.json

you're getting files like

../../../json/iamfoo.json

A much safer strategy would be to use something like os.path or pathlib.

Upvotes: 5

Related Questions