Home > Software design >  How to write csv inside a loop python
How to write csv inside a loop python

Time:01-04

i've done got my outputs for the csv file, but i dont know how to write it into csv file because output result is numpy array

def find_mode(np_array) :                                     
        vals,counts = np.unique(np_array, return_counts=True)    
        index = np.argmax(counts)                               
        return(vals[index])                                      



folder = ("C:/Users/ROG FLOW/Desktop/Untuk SIDANG TA/Sudah Aman/testbikincsv/folderdatacitra/*.jpg")
for file in glob.glob(folder):
    a = cv2.imread(file)
    rows = a.shape[0]
    cols = a.shape[1]
    middlex = cols/2                    
    middley = rows/2                     
    middle = [middlex,middley]
    titikawalx = middlex - 10             
    titikawaly = middley - 10
    titikakhirx = middlex   10           
    titikakhiry = middley   10
    crop = a[int(titikawaly):int(titikakhiry), int(titikawalx):int(titikakhirx)]
    c = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)
    H,S,V = cv2.split(c)
    hsv_split = np.concatenate((H,S,V),axis=1)
    Modus_citra = (find_mode(H))       #how to put this in csv
     

my outputs is modus citra which is array np.uint8, im trying to put it on csv file but im still confused how to write it into csv because the result in loop.

can someone help me how to write it into csv file ? i appreciate every help

CodePudding user response:

Run your loop, and put the data into lists

eg. mydata = [result1,result2,result3]

Then use csv.writerows(mydata) to write your list into csv rows

https://docs.python.org/3/library/csv.html#csv.csvwriter.writerows

CodePudding user response:

You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma. For example:

import numpy as np

my_array = np.array([1,2,3,4,5,6,7,8,9,10])

my_file = np.savetxt('randomtext.csv', my_array, delimiter = ',', fmt = '%d')

print(my_file)

  • Related