how to write output from python in different columns in CSV?

Question:

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`
Asked By: Volcano

||

Answers:

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"])


Answered By: Ryo Suzuki

This should be able to solve the problem.

You can always create a list of dictionary, store values in it and then write it to csv.

Here is a code that does that

import os
import csv
result_list = []
for path, dir_folder, files in os.walk('./test_folder'):
    raw_exists = "No"
    for file_name in files:
        if file_name.endswith('raw.txt'):
            raw_exists="Yes"
            break  
    row_dict={
        "Folder Name": os.path.basename(path),
        "Raw exists": raw_exists
    }
    result_list.append(row_dict)

with open('test.csv', 'w', encoding='utf8', newline='') as output_file:
    fc = csv.DictWriter(output_file, fieldnames=result_list[0].keys())
    fc.writeheader()
    fc.writerows(result_list)

Answered By: Hassan Jalil

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"])
Answered By: Martin Evans
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.