pythonfilepprint

Writing output of a text summarizer to a file replaces the previous summary


I am trying to write output of pprint to a file, but while doing so it replaces my previous output.

def summarize_snippets(seg):
  
  for  seg in truncated_sentence:
    input_text = ' '.join(seg) 
    summary_text = summarizer(input_text, min_length=50, max_length=80)
    summ = summary_text[0].get('summary_text')
    pp.pprint(summary_text[0].get('summary_text'))
    with open("/content/drive/MyDrive/path/summary.txt", "w+") as summ_file:
      pp.pprint((summary_text[0].get('summary_text')), summ_file)

I want all that is displayed as output to be in the file not just the last one. I tried to put the write command out of the loop but it gives error. Is there a better way to achieve this?

I tried to write to file while calling the function summarize_snippets(seg), it still is overwriting the previous output.

with open("/content/drive/MyDrive/crystal_ball/output/summary/summary.txt", "w+") as summ_file:
  pp.pprint(summarize_snippets (seg), summ_file)

Solution

  • I solved my problem with a simple fix as below -

        def summarize_snippets(joined_sentence):
      summ_text= [] 
      for  seg in joined_sentence:
        #input_text = seg
        summary_text = summarizer(seg, min_length=50, max_length=80)
        summ = summary_text[0].get('summary_text')
        summ_text.append(summ)
        pp.pprint(summary_text[0].get('summary_text'))
      with open('/content/drive/MyDrive/path/summary.txt', 'w') as f:
        for item in summ_text:
            f.write("%s\n\n\n\n\n\n" % item)