Python Forum

Full Version: Python code to read second line from CSV files and create a master CSV file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a folder lets say as 'input_Folder' which has a list of CSV files with data. I'm trying to write a python code which reads this list of CSV files from the input_folder and creates a master CSV file with two columns.

The columns in the master CSV files are 'Scenario' and 'Status'

Column Name requirement are as follows,
Scenario = Name of the file from the directory and
Status = if the file has a value in the second row of second column then populate as 'Pass' else 'Fail'
Below is my code. After executing the code i'm able to see Master CSV created but with empty lines. I'm quite new to python so could somebody help me out here please

import os
import csv

path = (Input file path)

with open(SUMMARY.csv", 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['SCENARIO', 'STATUS'])
for files in os.walk(path):
for filename in files:
with open(input_file.csv") as csv_file: #checking if the code is working for
#one sample file
all_rows = list(csv_file)
line_count = 0
for row in all_rows[1:2]:
if line_count == 1:
if row[1].value == none:
writer.writerow([os.path.basename(filename).split(".")
[0],'PASS'])
else:
writer.writerow([os.path.basename(filename).split(".")
[0],'FAIL'])
line_count += 1
One way

#! /usr/bin/env python3
import csv
import os
from tabulate import tabulate

with open('summary.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(['SCENARIO', 'STATUS'])

files = os.listdir('input_folder')
for file in files:
    with open(f'input_folder/{file}', 'r') as csv_file:
        read_file = csv.reader(csv_file)

        for line in read_file:
            with open('summary.csv', 'a') as summary:
                if line[1] == ' ':
                    status = 'FAIL'
                else:
                    status = 'PASS'

                writer = csv.writer(summary)
                writer.writerow([f'input_folder/{file}', status])

with open('summary.csv', 'r') as file:
    read_file = csv.reader(file)
    print(tabulate(read_file, headers='firstrow'))
Output:
SCENARIO STATUS ----------------------- -------- input_folder/file_1.csv PASS input_folder/file_1.csv PASS input_folder/file_1.csv PASS input_folder/file_2.csv PASS input_folder/file_2.csv FAIL input_folder/file_2.csv PASS