Python 2.7 Read and Write CSV File

最近在分析报告,由于报告数目较多有100+,手动查看比较麻烦且费时,就用Python写了一个自动分析报告Pass/Fail的脚本,本来开始用Python 3.8+Pandas写好了, 但是目标机器上安装的是Python2.7,所以最终没有用Pandas.

这里主要分析的报告的测试结果,按照Pass和Fail进行分类,基于此,分析逻辑如下:

1.对于表头Header是否位于第一行需要判断,同时报告中无关行需要跳过;

2.测试结果位于最后一个Column,对这一列进行遍历,有一个Fail即判断为Fail,如果遍历完没有Fail,即为Pass;

3.根据分析结果将报告放到不同的文件夹,同时打印Summary.

import csv
import os
import shutil

# Create path for classification
reports_path = 'test'
reports_summary_path = 'test\\TestResultsSummary.csv'
pass_folder = reports_path + '\\Pass\\'
fail_folder = reports_path + '\\Fail\\'
dict_test_results = {}

# Create folder Pass/Fail
if not os.path.exists(pass_folder):
    os.makedirs(pass_folder)
if not os.path.exists(fail_folder):
    os.makedirs(fail_folder)

# Analyse and classify the reports
for file in os.listdir(reports_path):
    isFail = False
    isReport = False
    if file.endswith('.csv') and file.startswith('result'): # find CSV file
        orig_path = reports_path + '\\' + file
        print(file)
        with open(orig_path, 'r') as csvDataFile:
            csv_reader = csv.reader(csvDataFile)
            for row in csv_reader:
                if len(row) < 3:
                    continue
                if row[-1] == 'Result' or row[-1] == 'PassFail':
                    isReport = True
                if row[-1] == 'Fail' or row[-1] == 'FAIL':
                    isFail = True
                    break
        if isFail and isReport:
            shutil.move(orig_path, fail_folder + file)  # Move report to Fail folder
            dict_test_results[file] = 'Fail'
        elif ~isFail and isReport:
            shutil.move(orig_path, pass_folder + file)  # Move report to Pass folder
            dict_test_results[file] = 'Pass'

# output the test summary
fail_count = 0
pass_count = 0
with open(reports_summary_path, 'w', newline='') as csvFile:
    csv_writer = csv.writer(csvFile)
    for item, result in dict_test_results.items():
        if result == 'Fail':
            fail_count += 1
        if result == 'Pass':
            pass_count += 1
    csv_writer.writerow('Fail: ' + str(fail_count) + ',' + 'Pass: ' + str(pass_count))
    csv_writer.writerow('') # empty line
    csv_writer.writerow(['Test Item', 'Result'])
    for item, result in dict_test_results.items():
        csv_writer.writerow([item, result])

 

你可能感兴趣的:(Python 2.7 Read and Write CSV File)