Python JSON dump / append to .txt with each variable on new line Python JSON dump / append to .txt with each variable on new line python python

Python JSON dump / append to .txt with each variable on new line


Your question is a little unclear. If you're generating hostDict in a loop:

with open('data.txt', 'a') as outfile:    for hostDict in ....:        json.dump(hostDict, outfile)        outfile.write('\n')

If you mean you want each variable within hostDict to be on a new line:

with open('data.txt', 'a') as outfile:    json.dump(hostDict, outfile, indent=2)

When the indent keyword argument is set it automatically adds newlines.


To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

with g as outfile:  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.