简体   繁体   中英

How to write to a text or csv file in python?

In images folder, I have 10 images of my face and I used face detection for each image in the folder. How can I put these results from my code below in a CSV file or a text file?

########     Full code face detection ################
from cv2 import *
import numpy
import glob
import sys
import random

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

path = "C:\Users\laptop\PycharmProjects\TestProjects\images\*.jpg"

for file in glob.glob(path):

    a= imread(file)
    Green = a[:, :, 1]  

    faces = face_cascade.detectMultiScale(Green, 1.3, 5) 

    for (x, y, w, h) in faces:

        roi_gray = Green[y:y + h, x:x + w]


    avg_color_per_row = numpy.average(roi_gray, axis=0)

    avg_color = numpy.average(avg_color_per_row, axis=0)

    print(avg_color)

######### the results that I obtained like this ############ 
69.91705606204184
70.66349480968857
69.041945839532
70.1554508228386
70.99404075355632
70.78112050920586
70.3311333247896
70.55470990048913
69.97209406638471
69.85739459182365

As Shiva answered above, you can use the csv.writer to output your result as a Csv file. This would be the pythonic way. There is a simpler solution as well.

Both Windows and *Nix Os'es support command redirection (eg: redirect windows cmd stdout ). You can use this technique to create a csv file based on the output of your program.

Explore modifying the last statement ( print(avg_color) ) to match the desired csv output and when you run the script redirect the output (via > ) to a csv file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM