Why does my text file keep overwriting the data on it?

w overwrites, open with a to append or open the file once outside the loop:

append:

while True:
    posts = requests.get(posts['paging']['next']).json()
    #print posts
    with open('test121.txt', 'a') as outfile:
        json.dump(posts, outfile)

Open once outside the loop:

with open('test121.txt', 'w') as outfile:
    while True:
        posts = requests.get(posts['paging']['next']).json()
        #print posts
        json.dump(posts, outfile)

It makes more sense to use the second option, if you are going to be running the code multiple times then you can open with a outside the loop also, if the file does not exist it will be created, if it does data will be appended

Leave a Comment