How to write content to a directory from python script

Hi experts.
Would like to save the content to a file rather than displaying it from python script. Since I'm new to python pls help me
Have attached a python script. right now it prints the content to stdout.

# I think, this line
self._display.display(json.dumps(output, indent=4, sort_keys=True))

Open in new window


Is it possible to have a variable declared for directory for json file location and write the file there?

Source File location:
https://codeclimate.com/github/ansible/ansible/lib/ansible/plugins/callback/json.py

thanks in advance.
json.py
enthuguyAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

peprCommented:
The json.dumps returns a string. So, you just write that string to the file of your choice. You need to know the filename. It is a good idea to store it into a variable like fname first -- then the code is usually easier to maintain when modified later. In principle, you open the file for writing, write the string into, and close it. In Python, you do it like this:
    fname = 'my_file.txt'
    with open(fname, 'w') as f:
        f.write(json.dumps(output, indent=4, sort_keys=True))

Open in new window


The with construct wraps the file object and ensures that the f will be closed automatically.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
enthuguyAuthor Commented:
Thanks Pepr,
for some reason, its not creating the json dump. Have attached the updated file. could you pls help :)
json.py
0
enthuguyAuthor Commented:
Worked fine. Thanks so much
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Ansible

From novice to tech pro — start learning today.