Home > database >  Python Export Dictionary to CSV
Python Export Dictionary to CSV

Time:11-02

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 csv file separate each letter into new row. I also need to add new key values for the filename, but I dont know how to get the image filename (input is images). I used the search bar searching for similar case/recommended solution but still stumped. Thanks in advance.

with open('glaresss_result.csv','wt') as f:
f.write(",".join(res1.keys())   "\n")
for imgpath in glob.glob(os.path.join(TARGET_DIR, "*.png")):
    res1,res = send_request_qcglare(imgpath)
    for row in zip(*res1.values()):
        f.write(",".join(str(n) for n in row)   "\n")
f.close()

dictionary res1 printed during the iteration returns:

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

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

  • glare brightness
  • Passed Passed
  • Passed Passed
  • Passed. Passed

But the current output looks like this:

Current output in csv

CodePudding user response:

Few things I changed.

  • w is enough, since t for text mode is default
  • no need to close the csv when using a context manager
  • no need for zip and str(n) for n in row. Just join the 2 values of the dictionary

UPDATED

with open('glaresss_result.csv','w') as f: 
    f.write(",".join([*res1]   ['filename'])   "\n") # replace filename with whatever columnname you want
    for imgpath in glob.glob(os.path.join(TARGET_DIR, "*.png")):
        res1,res = send_request_qcglare(imgpath)
        f.write(",".join([*res1.values()]   [imgpath])   "\n") # imgpath (which needs to be a string) will be the value of each row, replace with whatever you suits

CodePudding user response:

If you plan to do more with data, you might want to check out the pandas library. In your use case p.ex DataFrame.from_records

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.from_records.html

It provides a lot of out of the box functionalities to read, transform and write data.

import pandas as pd
results = []
for imgpath in glob.glob(os.path.join(TARGET_DIR, "*.png")):
    res1,res = send_request_qcglare(imgpath)
    result.append(res1)

df = pd.DataFrame.from_records(results)
df.to_csv("glaresss_result.csv", index=False)
  • Related