Home > Mobile >  Python Saving Each Result on New Line to CSV
Python Saving Each Result on New Line to CSV

Time:09-27

I'm new in Python and I've been trying to create csv file and save each result in a new row. The results consist of several rows and each line should be captured in csv. However, my output only saves the last rows of the result and overwritten all the previous rows. I think my approach is not the correct one but I'm stuck here and need helps. I use the search bar searching for similar case/recommended solution but still stumped. Thanks in advance.

  for i in os.listdir(TARGET_DIR):
  # if it ends with '.png'
  if i.endswith(".png"):
    imgpath = os.path.join(TARGET_DIR, i)
    res1,res = send_request_qcglare(imgpath)
    print(res1)
    
    with open('C:/Users/Folder/glare_result.csv','wt') as f:
        w = csv.writer(f)
        for row in res1.items():
            w.writerow(row)  

The results should be like this (got 3 rows):-

  • {'glare': 'Passed', 'brightness': 'Passed'}
  • {'glare': 'Passed', 'brightness': 'Passed'}
  • {'glare': 'Passed', 'brightness': 'Passed'}

The CSV is as attached.

CSV file

CodePudding user response:

Open the file (and CSV writer) first, then write to it in the loop:

import csv
import glob
import os

with open("C:/Users/Folder/glare_result.csv", "wt") as f:
    w = csv.writer(f)
    for imgpath in glob.glob(os.path.join(TARGET_DIR, "*.png")):
        res1, res = send_request_qcglare(imgpath)
        print(res1)
        for row in res1.items():
            w.writerow(row)

CodePudding user response:

In open() function change the mode from 'wt' to 'wa'

  • Related