how to read all folder names in directory and write folder names as header in CSV python?

Viewed 28

I am working with images to extract data into CSV. but currently, I want to name the header of CSV as an image folder name. The structure is this

Image

The structure for my CSV file looks like this

as

My code is

import glob
import os
files = glob.glob('/content/drive/MyDrive/YOLO_T_ID/yolov5/runs/detect/exp5/crops/**/*.jpg', recursive=True)

for f in files:
 dir_path = os.path.dirname(os.path.abspath(files)) 
 print(f)
1 Answers

Why not simply using os.listdir ?

import os
import csv

crops_dir = r"C:\Users\abokey\Desktop\crops"
img_folder_names = os.listdir(crops_dir)

with open(crops_dir+r'\output_csv.csv', 'w', newline='') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(img_folder_names)

# Output :

enter image description here

Related