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?
 
peprConnect With a Mentor Commented:
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.