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

My code creates a dictionary, which is then stored in a variable. I want to write each dictionary to a JSON file, but I want each dictionary to be on a new line.

My dictionary:

hostDict = {"key1": "val1", "key2": "val2", "key3": {"sub_key1": "sub_val2", "sub_key2": "sub_val2", "sub_key3": "sub_val3"}, "key4": "val4"}

Part of my code:

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

This appends each dictionary to 'data.txt' but it does so inline. I want each dictionary entry to be on new line. Any advice would be appreciated.

This question is related to python json append newline dump

The answer is


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.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to append

List append() in for loop ValueError: all the input arrays must have same number of dimensions Append a tuple to a list - what's the difference between two ways? How merge two objects array in angularjs? How to add an element at the end of an array? Appending a list or series to a pandas DataFrame as a row? Can someone explain how to append an element to an array in C programming? How to append elements at the end of ArrayList in Java? Append value to empty vector in R? How to append new data onto a new line

Examples related to newline

How can I insert a line break into a <Text> component in React Native? Print "\n" or newline characters as part of the output on terminal Using tr to replace newline with space How to write one new line in Bitbucket markdown? Line break in SSRS expression How to insert a new line in Linux shell script? Replace CRLF using powershell How to write new line character to a file in Java What is the newline character in the C language: \r or \n? How to print values separated by spaces instead of new lines in Python 2.7

Examples related to dump

Python JSON dump / append to .txt with each variable on new line Save Screen (program) output to a file How to restore PostgreSQL dump file into Postgres databases? Dump Mongo Collection into JSON format How can I convert an MDB (Access) file to MySQL (or plain SQL file)? kill -3 to get java thread dump Difference between javacore, thread dump and heap dump in Websphere What is the JavaScript equivalent of var_dump or print_r in PHP? List of tables, db schema, dump etc using the Python sqlite3 API Convert a string representation of a hex dump to a byte array using Java?