Home > Mobile >  how to write output from python in different columns in CSV?
how to write output from python in different columns in CSV?

Time:09-14

I have the output of list1 in 1st column and I want list2 in 2nd column. How can I do this? Or does anyone has a better solution? list1 is for all folders (about 200 ) in directory which are automatically generated with os.mkdir(directory). Now I want in 2nd column to check each folder for a file with .raw.txt and print Yes/No in the 2nd column. here you can see my output in csv

´   
    for list1 in fieldnames:
        for path, dir_folder, files in os.walk(path):
            for files in dir_folder:
                w.writerow(files.split())

    for list2 in fieldnames:
        for files in os.listdir(path):
            try:
                if os.path.exists("*\\raw.txt"):
                    print("Yes")
                else:
                    print("No")
            except:
                continue`

CodePudding user response:

Does this do what you're looking for?:

for path, dir_folder, files in os.walk(path):
    for file in files:
        w.writerow([dir_folder, "Yes" if file[-8:] == ".raw.txt" else "No"])


CodePudding user response:

To create a CSV file showing which folders contain a file ending raw.txt you could do the following:

import csv
import os

path = '/'

with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    
    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            if filename.endswith("raw.txt"):
                csv_output.writerow([dirpath, "Yes"])
                break
        else:
            csv_output.writerow([dirpath, "No"])
  • Related