【Web_办公自动化_Python3_Webdriver_Gooey_批量统计文件行数】通过目录,解析文件名/解析sheets名称/获取sheet行数/通过GUI按钮模式,统计测试用例条数

该Python脚本利用Gooey库创建图形用户界面,包括文件选择器和目录选择器等控件。脚本用于遍历指定目录下的CSV和XLSX文件,读取Excel文件的sheet,并统计每张工作表的非空行数。结果保存到文本文件中。
摘要由CSDN通过智能技术生成

#!/usr/bin/env/python3
# -*- coding:utf-8 -*-

"""
常用控件:
| 控件名        | 控件类型    |
| --------   | -----:   |
| FileChooser      | 文件选择器 |
| MultiFileChooser | 文件多选器|
| DirChooser       | 目录选择器 |
| MultiDirChooser  | 目录多选器 |
| FileSaver        | 文件保存      |
| DateChooser        | 日期选择      |
| TextField        | 文本输入框      |
| Dropdown        | 下拉列表      |
| Counter        | 计数器      |
| CheckBox        | 复选框      |
| RadioGroup        | 单选框      |
"""
# 通过目录,获取文件名称;通过名称获取sheet名称,通过sheet名称获取文件行数。
from gooey import Gooey, GooeyParser
import os
import time
import openpyxl

test_file_path = r"C:\Users\Tese Case"

test_excle_path_name = r"C:\Users\TestCase.xlsx"

date = time.strftime("%Y-%m-%d", time.localtime(time.time()))
def print_and_write(*args, **kwargs):
    with open(f"./测试用例统计_{date}.txt", "a", encoding="utf-8") as f:
        print(*args, end=kwargs.get("end", "\n"))
        for i in args:
            f.write(i)
            f.write(kwargs.get("end", "\n"))

def get_all_file_name(dirPath=test_file_path):
    "批量读取文件名称"
    csv_list = []
    xlsx_list = []
    other_list = []
    for root, dirs, files in os.walk(dirPath, topdown=False, followlinks=False):
        print(root, files)
        for file in files:
            file_type = str(file).split(".")[-1]
            file_path_name = os.path.join(root, file)
            if "csv" in file_type:
                csv_list.append(file_path_name)
            elif "xlsx" in file_type:
                xlsx_list.append(file_path_name)
            else:
                other_list.append(file_path_name)
    res_dict = dict([("csv_list", csv_list), ("xlsx_list", xlsx_list), ("other_list", other_list)])
    print(res_dict["xlsx_list"])
    return res_dict

def get_all_excle_sheet(file_name=test_excle_path_name):
    from collections import Counter
    wb_obj = openpyxl.load_workbook(file_name)
    all_tatal_count = 0
    all_name_list = []
    sheetnames = wb_obj.sheetnames
    for sheet_name in sheetnames:
        # ws = wb_obj.get_sheet_by_name(sheet_name)
        ws = wb_obj[sheet_name]
        # print('工作表:', sheetnames)
        # print('工作表列数:', ws.max_column)
        # print('工作表行数:', ws.max_row)
        cur_row = ws.max_row
        flag = True
        # 排除空行
        while flag:
            rowdata = []
            # for i in range(1, ws.max_column+1):
            for i in range(1, 13):
                cellvalue = ws.cell(row=cur_row, column=i).value
                rowdata.append(cellvalue)
            None_count = Counter(rowdata)  # {None: 16}
            if None_count[None] > 10 and cur_row > 1:
                cur_row = cur_row-1
            else:
                # print(cur_row, rowdata, None_count[None], end="")
                flag = False
        max_row_count = min(cur_row, ws.max_row)
        all_name_list.append(f"{sheet_name}--{str(max_row_count)}")
        all_tatal_count += max_row_count
    res_dict = dict(all_tatal_count=all_tatal_count, all_sheet_name_dict=all_name_list)
    print(res_dict, end="\n")
    return res_dict

def get_all_excle_sheet_count(dirPath=test_file_path, list_name="xlsx_list"):  # openpyxl 不支持CSV文件
    file_path_name_dict = get_all_file_name(dirPath)
    for path_name in file_path_name_dict[list_name]:
        print(path_name)
        print_and_write("今日分割线".center(50, "-"))
        print_and_write("\n记录日期:{}".format(time.strftime("%Y-%m-%d %H%M%S", time.localtime(time.time()))))
        print_and_write("文件路径:{}".format(os.path.dirname(path_name)))
        print_and_write("文件名称:{}".format(os.path.basename(path_name)))
        res_excle_dict = get_all_excle_sheet(file_name=path_name.replace("\\\\", "\\"))
        print_and_write("文件统计:{}".format(res_excle_dict))
@Gooey(
    program_name="Test Tools",
    richtext_controls=True,
    encoding="utf-8",
    progress_regex=r"^progress: (\d+)%$",
    language="chinese",
    show_sidebar=True,
    dump_build_config=True
)
def Mytest():
    settings_msg = 'TestDemo'
    parser = GooeyParser(description=settings_msg)

    subs = parser.add_subparsers(help='commands', dest='command')

    my_parser = subs.add_parser('统计用例条数')
    my_parser.add_argument("dirPath", metavar='文件夹路径', help="请选择文件夹路径", widget="DirChooser")

    my_parser.add_argument("fileType", metavar='文件类型', help="请选择文件类型", choices=['xlsx_list', 'csv_list', 'other_list'], default='xlsx_list')

    args = parser.parse_args()
    get_all_excle_sheet_count(dirPath=args.dirPath, list_name=args.fileType)
    print(args, flush=True)  # flush=True在打包的时候会用到


if __name__ == '__main__':
    Mytest()

效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值