title: Writing Json in for loop in Python
body: <p>I am downloading Json files from an API, I use the following code to write the JSON. Each item the loop gives me a JSON file. I need to save it and extract entities from the appended JSON file using a loop.</p>
  
  <pre><code>for item in style_ls:
      dat = get_json(api, item)
      specs_dict[item] = dat
      with open("specs_append.txt", "a") as myfile:
          json.dump(dat, myfile)
          myfile.close()
      print item
  
  with open ("specs_data.txt", "w") as my file:
      json.dump(spec_dict, myfile)
      myfile.close()
  </code></pre>
  
  <p>I know that I cannot get a valid JSON format from the <code>specs_append.txt</code>, but I can get one from the <code>specs_data.txt</code>. I am doing the first one just because my program needs atleast 3-4 days to complete and there are high chances that my system may shutdown. So is there anyway I can do this efficiently ? </p>
  
  <p>If not is there anyway I can extract it from <code>specs_append.txt</code> <code>&lt;{JSON}{JSON}&gt;</code> format (which is not a valid JSON format)?</p>
  
  <p>If not should I write specs_dict to a txt file every time in the loop, so that even if program gets terminated i can start if from that point in loop and still get a valid json format?</p>