0

I'm trying to make a python script that writes a given number of JSON objects to a text file. Every object needs to be on its own line.

I want to be able to loop X amount of times and every time I iterate through that loop I want to write a JSON Object to a utf8 encoded text file. Each JSON object will be on its own line.

import json

count = 5
while(count > 0):
    data = {
        "Address":[{
            "Street":"Main St",
            "State":"WY"
        }],
        "Name":"Jim",
        "LastName":"Beam"
    }
    with open('data.txt', 'w') as outfile:
        json.dump(data, outfile)
    count = count -1;

This keeps overwriting the entire file so it ends up overwriting the file 5 times over.

I want the file to look like this:

{"Address":[{"Street":"Main St", "State":"WY"}], "Name":"Jim", "LastName":"Beam"}
{"Address":[{"Street":"Main St", "State":"WY"}], "Name":"Jim", "LastName":"Beam"}
{"Address":[{"Street":"Main St", "State":"WY"}], "Name":"Jim", "LastName":"Beam"}
{"Address":[{"Street":"Main St", "State":"WY"}], "Name":"Jim", "LastName":"Beam"}
{"Address":[{"Street":"Main St", "State":"WY"}], "Name":"Jim", "LastName":"Beam"}
Clev_James23
  • 171
  • 1
  • 3
  • 15
  • That's **not** a JSON file. Why not build an array and write *that* out? – jonrsharpe Jul 17 '19 at 18:18
  • Whats reading it needs each json object to be its own line or separated by some other delimiter and not in a format of an array – Clev_James23 Jul 17 '19 at 18:28
  • Check the available file modes in the docs: https://docs.python.org/3/library/functions.html#open `'a'` and not `'w'` is probably what you want. – dmmfll Jul 17 '19 at 18:42

1 Answers1

0

Everytime the loop is iterated it opens up a new file, therefore it rewrites the file until count >0 and hence, there must be an append method to append the content to the existing file.

Krishna
  • 11
  • 2