• 开源一个Python处理csv文件的GUI程序代码模板


    一、PyQt5的.ui文件

    ReadCsvStringOutputAvg.ui

    查看代码
    
    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
     <class>MainWindowAresRT</class>
     <widget class="QMainWindow" name="MainWindowAresRT">
      <property name="geometry">
       <rect>
        <x>0</x>
        <y>0</y>
        <width>640</width>
        <height>480</height>
       </rect>
      </property>
      <property name="minimumSize">
       <size>
        <width>640</width>
        <height>480</height>
       </size>
      </property>
      <property name="maximumSize">
       <size>
        <width>1920</width>
        <height>1080</height>
       </size>
      </property>
      <property name="windowTitle">
       <string>读取Cellular_Z日志的信号平均值工具(作者:康冕峰)</string>
      </property>
      <widget class="QWidget" name="centralwidget">
       <widget class="QTextEdit" name="textEdit_logimport_directory">
        <property name="geometry">
         <rect>
          <x>180</x>
          <y>30</y>
          <width>270</width>
          <height>60</height>
         </rect>
        </property>
        <property name="minimumSize">
         <size>
          <width>270</width>
          <height>60</height>
         </size>
        </property>
        <property name="font">
         <font>
          <pointsize>10</pointsize>
         </font>
        </property>
       </widget>
       <widget class="QPushButton" name="pushButton_openfile">
        <property name="geometry">
         <rect>
          <x>520</x>
          <y>30</y>
          <width>91</width>
          <height>71</height>
         </rect>
        </property>
        <property name="font">
         <font>
          <pointsize>12</pointsize>
         </font>
        </property>
        <property name="text">
         <string>打开目录</string>
        </property>
       </widget>
       <widget class="QLabel" name="label_input">
        <property name="geometry">
         <rect>
          <x>40</x>
          <y>20</y>
          <width>111</width>
          <height>51</height>
         </rect>
        </property>
        <property name="font">
         <font>
          <family>Arial</family>
          <pointsize>12</pointsize>
         </font>
        </property>
        <property name="text">
         <string>处理报告目录:</string>
        </property>
       </widget>
       <widget class="QLabel" name="label_output">
        <property name="geometry">
         <rect>
          <x>40</x>
          <y>320</y>
          <width>111</width>
          <height>51</height>
         </rect>
        </property>
        <property name="font">
         <font>
          <pointsize>12</pointsize>
         </font>
        </property>
        <property name="layoutDirection">
         <enum>Qt::LeftToRight</enum>
        </property>
        <property name="text">
         <string>正在执行命令:</string>
        </property>
       </widget>
       <widget class="QLabel" name="label_bottom">
        <property name="geometry">
         <rect>
          <x>160</x>
          <y>330</y>
          <width>421</width>
          <height>41</height>
         </rect>
        </property>
        <property name="font">
         <font>
          <pointsize>12</pointsize>
         </font>
        </property>
        <property name="autoFillBackground">
         <bool>true</bool>
        </property>
        <property name="frameShadow">
         <enum>QFrame::Plain</enum>
        </property>
        <property name="lineWidth">
         <number>1</number>
        </property>
        <property name="text">
         <string>1)点击文件选择导入的目录 2)点击处理输出到Excel文件</string>
        </property>
       </widget>
       <widget class="QWidget" name="verticalLayoutWidget">
        <property name="geometry">
         <rect>
          <x>180</x>
          <y>160</y>
          <width>271</width>
          <height>121</height>
         </rect>
        </property>
        <layout class="QVBoxLayout" name="verticalLayout_1">
         <property name="sizeConstraint">
          <enum>QLayout::SetDefaultConstraint</enum>
         </property>
         <property name="leftMargin">
          <number>10</number>
         </property>
         <item>
          <widget class="QCheckBox" name="checkBox_download">
           <property name="font">
            <font>
             <pointsize>11</pointsize>
            </font>
           </property>
           <property name="text">
            <string>下行MAC总吞吐率(Mbps)</string>
           </property>
           <property name="checkable">
            <bool>false</bool>
           </property>
           <property name="checked">
            <bool>false</bool>
           </property>
          </widget>
         </item>
         <item>
          <widget class="QCheckBox" name="checkBox_upload">
           <property name="font">
            <font>
             <pointsize>11</pointsize>
            </font>
           </property>
           <property name="text">
            <string>上行MAC总吞吐率(Mbps)</string>
           </property>
           <property name="checkable">
            <bool>false</bool>
           </property>
           <property name="checked">
            <bool>false</bool>
           </property>
          </widget>
         </item>
         <item>
          <widget class="QCheckBox" name="checkBox_Signal_0">
           <property name="font">
            <font>
             <pointsize>11</pointsize>
            </font>
           </property>
           <property name="text">
            <string>透视的信号平均值(dBm)</string>
           </property>
           <property name="checkable">
            <bool>true</bool>
           </property>
           <property name="checked">
            <bool>true</bool>
           </property>
          </widget>
         </item>
        </layout>
       </widget>
       <widget class="QPushButton" name="pushButton_dispose">
        <property name="geometry">
         <rect>
          <x>520</x>
          <y>180</y>
          <width>91</width>
          <height>71</height>
         </rect>
        </property>
        <property name="font">
         <font>
          <pointsize>12</pointsize>
         </font>
        </property>
        <property name="text">
         <string>处理输出</string>
        </property>
       </widget>
       <widget class="QLabel" name="label_selected_filepath">
        <property name="geometry">
         <rect>
          <x>190</x>
          <y>40</y>
          <width>281</width>
          <height>31</height>
         </rect>
        </property>
        <property name="font">
         <font>
          <pointsize>12</pointsize>
         </font>
        </property>
        <property name="text">
         <string>TextLabel</string>
        </property>
       </widget>
      </widget>
      <widget class="QMenuBar" name="menubar">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>640</width>
         <height>23</height>
        </rect>
       </property>
       <widget class="QMenu" name="menu_file">
        <property name="title">
         <string>文件</string>
        </property>
        <widget class="QMenu" name="menurecently_import">
         <property name="title">
          <string>recently_import</string>
         </property>
         <addaction name="action_first_dir"/>
         <addaction name="action_second_dir"/>
         <addaction name="action_third_dir"/>
        </widget>
        <addaction name="action_directory_import"/>
        <addaction name="menurecently_import"/>
        <addaction name="separator"/>
       </widget>
       <widget class="QMenu" name="menu_help">
        <property name="title">
         <string>帮助</string>
        </property>
        <addaction name="action_about_help"/>
       </widget>
       <widget class="QMenu" name="menu_process">
        <property name="title">
         <string>处理</string>
        </property>
        <addaction name="action_read_start"/>
       </widget>
       <widget class="QMenu" name="menu_reset">
        <property name="title">
         <string>重置</string>
        </property>
        <addaction name="action_test_reset"/>
       </widget>
       <addaction name="menu_file"/>
       <addaction name="menu_process"/>
       <addaction name="menu_reset"/>
       <addaction name="menu_help"/>
      </widget>
      <widget class="QStatusBar" name="statusbar"/>
      <action name="action_directory_import">
       <property name="text">
        <string>directory_import</string>
       </property>
       <property name="font">
        <font>
         <family>Arial</family>
         <pointsize>10</pointsize>
        </font>
       </property>
      </action>
      <action name="action_read_start">
       <property name="text">
        <string>read_output</string>
       </property>
       <property name="font">
        <font>
         <family>Arial</family>
         <pointsize>10</pointsize>
        </font>
       </property>
      </action>
      <action name="action_about_help">
       <property name="text">
        <string>about_help</string>
       </property>
      </action>
      <action name="action_first_dir">
       <property name="text">
        <string>first_dir</string>
       </property>
      </action>
      <action name="action_second_dir">
       <property name="text">
        <string>second_dir</string>
       </property>
      </action>
      <action name="action_third_dir">
       <property name="text">
        <string>third_dir</string>
       </property>
      </action>
      <action name="action_test_reset">
       <property name="text">
        <string>tset_reset</string>
       </property>
      </action>
     </widget>
     <resources/>
     <connections>
      <connection>
       <sender>pushButton_dispose</sender>
       <signal>clicked()</signal>
       <receiver>textEdit_logimport_directory</receiver>
       <slot>hide()</slot>
       <hints>
        <hint type="sourcelabel">
         <x>565</x>
         <y>238</y>
        </hint>
        <hint type="destinationlabel">
         <x>314</x>
         <y>82</y>
        </hint>
       </hints>
      </connection>
      <connection>
       <sender>checkBox_upload</sender>
       <signal>clicked(bool)</signal>
       <receiver>label_selected_filepath</receiver>
       <slot>hide()</slot>
       <hints>
        <hint type="sourcelabel">
         <x>319</x>
         <y>242</y>
        </hint>
        <hint type="destinationlabel">
         <x>330</x>
         <y>78</y>
        </hint>
       </hints>
      </connection>
      <connection>
       <sender>checkBox_download</sender>
       <signal>clicked(bool)</signal>
       <receiver>label_selected_filepath</receiver>
       <slot>hide()</slot>
       <hints>
        <hint type="sourcelabel">
         <x>319</x>
         <y>205</y>
        </hint>
        <hint type="destinationlabel">
         <x>330</x>
         <y>78</y>
        </hint>
       </hints>
      </connection>
      <connection>
       <sender>checkBox_Signal_0</sender>
       <signal>clicked(bool)</signal>
       <receiver>label_selected_filepath</receiver>
       <slot>hide()</slot>
       <hints>
        <hint type="sourcelabel">
         <x>319</x>
         <y>279</y>
        </hint>
        <hint type="destinationlabel">
         <x>330</x>
         <y>78</y>
        </hint>
       </hints>
      </connection>
     </connections>
    </ui>

    ReadCsvStringOutputAvg.py

    查看代码
    # -*- coding: utf-8 -*-
    # 自动读取手机应用“Cellular_Z的csv日志格式”计算rsrp平均值的脚本
    # Form implementation generated from reading ui file 'ReadCsvStringOutputAvg.ui'
    #
    # Created by: PyQt5 UI code generator 5.15.4
    #
    # WARNING: Any manual changes made to this file will be lost when pyuic5 is
    # run again.  Do not edit this file unless you know what you are doing.
    
    from __future__ import division
    from PyQt5 import QtCore, QtGui, QtWidgets
    
    import os
    import pandas as pd
    import re
    # 全局变量
    filePath_parent="空"
    filePath_select="空"
    
    
    class Ui_MainWindowAresRT(object):
        cls_fileName ="空"
        log_dir_list = []  # 测试人员可重命名的包含有大量.csv日志文件的,目录名称组成的列表
        csvlog_absfilepath = []  # 待处理所有的.csv文件构成的列表  
        def setupUi(self, MainWindowAresRT):
            MainWindowAresRT.setObjectName("MainWindowAresRT")
            MainWindowAresRT.resize(640, 480)
            MainWindowAresRT.setMinimumSize(QtCore.QSize(640, 480))
            MainWindowAresRT.setMaximumSize(QtCore.QSize(1920, 1080))
            self.centralwidget = QtWidgets.QWidget(MainWindowAresRT)
            self.centralwidget.setObjectName("centralwidget")
            self.textEdit_logimport_directory = QtWidgets.QTextEdit(self.centralwidget)
            self.textEdit_logimport_directory.setGeometry(QtCore.QRect(180, 30, 270, 60))
            self.textEdit_logimport_directory.setMinimumSize(QtCore.QSize(270, 60))
            font = QtGui.QFont()
            font.setPointSize(10)
            self.textEdit_logimport_directory.setFont(font)
            self.textEdit_logimport_directory.setObjectName("textEdit_logimport_directory")
            self.pushButton_openfile = QtWidgets.QPushButton(self.centralwidget)
            self.pushButton_openfile.setGeometry(QtCore.QRect(520, 30, 91, 71))
            font = QtGui.QFont()
            font.setPointSize(12)
            self.pushButton_openfile.setFont(font)
            self.pushButton_openfile.setObjectName("pushButton_openfile")
            self.label_input = QtWidgets.QLabel(self.centralwidget)
            self.label_input.setGeometry(QtCore.QRect(40, 20, 111, 51))
            font = QtGui.QFont()
            font.setFamily("Arial")
            font.setPointSize(12)
            self.label_input.setFont(font)
            self.label_input.setObjectName("label_input")
            self.label_output = QtWidgets.QLabel(self.centralwidget)
            self.label_output.setGeometry(QtCore.QRect(40, 320, 111, 51))
            font = QtGui.QFont()
            font.setPointSize(12)
            self.label_output.setFont(font)
            self.label_output.setLayoutDirection(QtCore.Qt.LeftToRight)
            self.label_output.setObjectName("label_output")
            self.label_bottom = QtWidgets.QLabel(self.centralwidget)
            self.label_bottom.setGeometry(QtCore.QRect(160, 330, 421, 41))
            font = QtGui.QFont()
            font.setPointSize(12)
            self.label_bottom.setFont(font)
            self.label_bottom.setAutoFillBackground(True)
            self.label_bottom.setFrameShadow(QtWidgets.QFrame.Plain)
            self.label_bottom.setLineWidth(1)
            self.label_bottom.setObjectName("label_bottom")
            self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
            self.verticalLayoutWidget.setGeometry(QtCore.QRect(180, 160, 271, 121))
            self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
            self.verticalLayout_1 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
            self.verticalLayout_1.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
            self.verticalLayout_1.setContentsMargins(10, 0, 0, 0)
            self.verticalLayout_1.setObjectName("verticalLayout_1")
            self.checkBox_download = QtWidgets.QCheckBox(self.verticalLayoutWidget)
            font = QtGui.QFont()
            font.setPointSize(11)
            self.checkBox_download.setFont(font)
            self.checkBox_download.setCheckable(False)
            self.checkBox_download.setChecked(False)
            self.checkBox_download.setObjectName("checkBox_download")
            self.verticalLayout_1.addWidget(self.checkBox_download)
            self.checkBox_upload = QtWidgets.QCheckBox(self.verticalLayoutWidget)
            font = QtGui.QFont()
            font.setPointSize(11)
            self.checkBox_upload.setFont(font)
            self.checkBox_upload.setCheckable(False)
            self.checkBox_upload.setChecked(False)
            self.checkBox_upload.setObjectName("checkBox_upload")
            self.verticalLayout_1.addWidget(self.checkBox_upload)
            self.checkBox_Signal_0 = QtWidgets.QCheckBox(self.verticalLayoutWidget)
            font = QtGui.QFont()
            font.setPointSize(11)
            self.checkBox_Signal_0.setFont(font)
            self.checkBox_Signal_0.setCheckable(True)
            self.checkBox_Signal_0.setChecked(True)
            self.checkBox_Signal_0.setObjectName("checkBox_Signal_0")
            self.verticalLayout_1.addWidget(self.checkBox_Signal_0)
            self.pushButton_dispose = QtWidgets.QPushButton(self.centralwidget)
            self.pushButton_dispose.setGeometry(QtCore.QRect(520, 180, 91, 71))
            font = QtGui.QFont()
            font.setPointSize(12)
            self.pushButton_dispose.setFont(font)
            self.pushButton_dispose.setObjectName("pushButton_dispose")
            self.label_selected_filepath = QtWidgets.QLabel(self.centralwidget)
            self.label_selected_filepath.setGeometry(QtCore.QRect(190, 40, 281, 31))
            font = QtGui.QFont()
            font.setPointSize(12)
            self.label_selected_filepath.setFont(font)
            self.label_selected_filepath.setObjectName("label_selected_filepath")
            MainWindowAresRT.setCentralWidget(self.centralwidget)
            self.menubar = QtWidgets.QMenuBar(MainWindowAresRT)
            self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 23))
            self.menubar.setObjectName("menubar")
            self.menu_file = QtWidgets.QMenu(self.menubar)
            self.menu_file.setObjectName("menu_file")
            self.menurecently_import = QtWidgets.QMenu(self.menu_file)
            self.menurecently_import.setObjectName("menurecently_import")
            self.menu_help = QtWidgets.QMenu(self.menubar)
            self.menu_help.setObjectName("menu_help")
            self.menu_process = QtWidgets.QMenu(self.menubar)
            self.menu_process.setObjectName("menu_process")
            self.menu_reset = QtWidgets.QMenu(self.menubar)
            self.menu_reset.setObjectName("menu_reset")
            MainWindowAresRT.setMenuBar(self.menubar)
            self.statusbar = QtWidgets.QStatusBar(MainWindowAresRT)
            self.statusbar.setObjectName("statusbar")
            MainWindowAresRT.setStatusBar(self.statusbar)
            self.action_directory_import = QtWidgets.QAction(MainWindowAresRT)
            font = QtGui.QFont()
            font.setFamily("Arial")
            font.setPointSize(10)
            self.action_directory_import.setFont(font)
            self.action_directory_import.setObjectName("action_directory_import")
            self.action_read_start = QtWidgets.QAction(MainWindowAresRT)
            font = QtGui.QFont()
            font.setFamily("Arial")
            font.setPointSize(10)
            self.action_read_start.setFont(font)
            self.action_read_start.setObjectName("action_read_start")
            self.action_about_help = QtWidgets.QAction(MainWindowAresRT)
            self.action_about_help.setObjectName("action_about_help")
            self.action_first_dir = QtWidgets.QAction(MainWindowAresRT)
            self.action_first_dir.setObjectName("action_first_dir")
            self.action_second_dir = QtWidgets.QAction(MainWindowAresRT)
            self.action_second_dir.setObjectName("action_second_dir")
            self.action_third_dir = QtWidgets.QAction(MainWindowAresRT)
            self.action_third_dir.setObjectName("action_third_dir")
            self.action_test_reset = QtWidgets.QAction(MainWindowAresRT)
            self.action_test_reset.setObjectName("action_test_reset")
            self.menurecently_import.addAction(self.action_first_dir)
            self.menurecently_import.addAction(self.action_second_dir)
            self.menurecently_import.addAction(self.action_third_dir)
            self.menu_file.addAction(self.action_directory_import)
            self.menu_file.addAction(self.menurecently_import.menuAction())
            self.menu_file.addSeparator()
            self.menu_help.addAction(self.action_about_help)
            self.menu_process.addAction(self.action_read_start)
            self.menu_reset.addAction(self.action_test_reset)
            self.menubar.addAction(self.menu_file.menuAction())
            self.menubar.addAction(self.menu_process.menuAction())
            self.menubar.addAction(self.menu_reset.menuAction())
            self.menubar.addAction(self.menu_help.menuAction())
    
            self.retranslateUi(MainWindowAresRT)
            self.pushButton_dispose.clicked.connect(self.textEdit_logimport_directory.hide)
            self.checkBox_upload.clicked['bool'].connect(self.label_selected_filepath.hide)
            self.checkBox_download.clicked['bool'].connect(self.label_selected_filepath.hide)
            self.checkBox_Signal_0.clicked['bool'].connect(self.label_selected_filepath.hide)
            ## 用户自定义手动填写代码部分
            self.pushButton_openfile.clicked.connect(self.open_file_dialogbox)
            self.pushButton_dispose.clicked.connect(self.read_and_output)           
            QtCore.QMetaObject.connectSlotsByName(MainWindowAresRT)
    
        def retranslateUi(self, MainWindowAresRT):
            _translate = QtCore.QCoreApplication.translate
            MainWindowAresRT.setWindowTitle(_translate("MainWindowAresRT", "读取Cellular_Z日志的信号平均值工具(作者:康冕峰)"))
            self.pushButton_openfile.setText(_translate("MainWindowAresRT", "打开目录"))
            self.label_input.setText(_translate("MainWindowAresRT", "处理报告目录:"))
            self.label_output.setText(_translate("MainWindowAresRT", "正在执行命令:"))
            self.label_bottom.setText(_translate("MainWindowAresRT", "1)点击文件选择导入的目录 2)点击处理输出到Excel文件"))
            self.checkBox_download.setText(_translate("MainWindowAresRT", "下行MAC总吞吐率(Mbps)"))
            self.checkBox_upload.setText(_translate("MainWindowAresRT", "上行MAC总吞吐率(Mbps)"))
            self.checkBox_Signal_0.setText(_translate("MainWindowAresRT", "透视的信号平均值(dBm)"))
            self.pushButton_dispose.setText(_translate("MainWindowAresRT", "处理输出"))
            self.label_selected_filepath.setText(_translate("MainWindowAresRT", "TextLabel"))
            self.menu_file.setTitle(_translate("MainWindowAresRT", "文件"))
            self.menurecently_import.setTitle(_translate("MainWindowAresRT", "recently_import"))
            self.menu_help.setTitle(_translate("MainWindowAresRT", "帮助"))
            self.menu_process.setTitle(_translate("MainWindowAresRT", "处理"))
            self.menu_reset.setTitle(_translate("MainWindowAresRT", "重置"))
            self.action_directory_import.setText(_translate("MainWindowAresRT", "directory_import"))
            self.action_read_start.setText(_translate("MainWindowAresRT", "read_output"))
            self.action_about_help.setText(_translate("MainWindowAresRT", "about_help"))
            self.action_first_dir.setText(_translate("MainWindowAresRT", "first_dir"))
            self.action_second_dir.setText(_translate("MainWindowAresRT", "second_dir"))
            self.action_third_dir.setText(_translate("MainWindowAresRT", "third_dir"))
            self.action_test_reset.setText(_translate("MainWindowAresRT", "tset_reset"))
        ## 用户自定义手动填写代码部分
        # 打开文件目录选择对话窗口
        def open_file_dialogbox(self):
            fileName, fileType = QtWidgets.QFileDialog.getOpenFileName(self, "请选取任意的一个文件作为路径输入使用", "D:\\", "All Files(*);;Text Files(*.txt)")
            '''
            参数一:设置GUI父组件
            参数二:QFileDialog的标题
            参数三:默认打开的目录,“.”点表示程序运行目录,/表示当前盘符根目录
            参数四:对话框的文件扩展名过滤器Filter,比如使用 Image files(*.jpg *.gif) 表示只能显示扩展名为.jpg或者.gif文件
            设置多个文件扩展名过滤,使用双引号隔开;
            “All Files(*);;PDF Files(*.pdf);;Text Files(*.txt)”
            选取文件夹 QFileDialog.getExistingDirectory()
            '''
            # 1.获取当前导入的目录
            # 是以 "PATH" 中最后一个 '/' 作为分隔符,分隔后,将索引为0的视为目录(路径),将索引为1的视为文件名
            global filePath_parent         
            filePath_parent,_ = os.path.split(fileName)
            global filePath_select 
            filePath_select = fileName
            # 再把变量赋值给类的静态变量
            self.cls_fileName = fileName
            # 2.从给定目录开始条件遍历
            if filePath_parent == "D:/":
                print("你选的路径是 D:\\ 可能会使得电脑卡死! 请重新选择。")
            elif filePath_parent == "C:/":
                print("你选的路径是 C:\\ 可能会使得电脑卡死! 请重新选择。")    
            elif (filePath_parent == "空") or (filePath_parent == ""):
                print("你还没有通过点击“文件”选择待导入处理的文件目录!")
            else:
            # 3.选择完文件路径后的处理
                print("已选择处理文件目录:"+ "\t" + self.cls_fileName)  # 调试用的会在黑窗口打印
                log_dir_list1 = os.listdir(filePath_parent)  #返回一个列表,包含目录和文件
                abs_path_list1 = abspath_preprocess(filePath_parent, log_dir_list1)  #1代表需要处理剔除文件的列表
                abs_path_list2 = listdir_post_process(abs_path_list1)    #2代表处理后的只含有目录的绝对路径列表   
                self.log_dir_list = abs_path_list2         
                # print(self.log_dir_list)
            # 4.设定方法的返回值
            return "-----执行 open_file_dialogbox 方法-----"
        def read_and_output(self):
            abs_csv_fileName_list = output_csvlog_absfilepath(self.log_dir_list)
            # 分类调用处理函数
            print(abs_csv_fileName_list)
            my_dict = cellz_rsrp_mean(abs_csv_fileName_list)  ##用户需自己设计的处理函数
            # 调用输出文件的函数 
            write_list_into_excel(my_dict)       ##用户需自己设计的处理函数
            return 
    
    # 定义一个方法用于拼接字符串,返回给定文件列表里的所有文件、目录的绝对路径
    def abspath_preprocess( str_path="", file_list=[] ):
        result_list = []
        for i in file_list:
            s = str_path +"/" + i  # 字符串拼接
            result_list.append(s)
        return result_list
    
    # 定义一个方法:输入一个路径的列表,只保留目录,剔除文件
    def listdir_post_process( dir_list=[] ):
        result_list = []
        count = 0
        for i in dir_list:
            if os.path.isdir(i): 
                result_list.append(i)
            elif os.path.isfile(i):
                count +=1
                print("------ 程序正在处理文件中{0} ------".format(count))
            else:
                pass  # TODO
        # 返回结果是只含有目录构成的列表
        return result_list
    
    # 定义一个方法:根据csv文件所在目录的列表,获取所有csv文件的绝对路径
    def output_csvlog_absfilepath( log_dir_list=[] ):
        csvlog_absfilepath = []  #创建1个空列表做容器
        for f in log_dir_list:  #遍历包含csv日志的目录绝对路径构成的列表
            fileNames = os.listdir(f)
            # print(fileNames)
            num = len(fileNames)  #获取列表元素个数
            for i in range(num):  #遍历单个的日志目录下的文件、目录
                kang = f+'/'+fileNames[i]
                # print(kang)
                if os.path.isfile(kang):  #判断是文件
                    if kang.lower().endswith(".csv"):  #判断是.csv文件,包含.CSV文件
                        csvlog_absfilepath.append(kang)  #添加到收集容器里
        # print(csvlog_absfilepath)  #打印输出显示所有待处理的CSV文件
        print("-----过滤待处理.csv文件已完成-----")
        return csvlog_absfilepath
    
    #  定义一个方法:根据输入的文件绝对路径构成的列表,返回文件的文件名.文件类型构成的列表
    def trans_absfilepath_to_filename( abs_filepath_list=[]):
        csvlog_filename = []  #创建1个空列表做容器
        for f in abs_filepath_list:    #遍历包含csv日志文件的绝对路径构成的列表
            _,_basename = os.path.split(f)   #将全路径分解为(文件夹,文件名)的元组
            csvlog_filename.append(_basename)
        return csvlog_filename
    
    # 计算输出 Cellular_Z信号强度 平均值到Excel文档
    # 输入一个csv文件的绝对路径的列表
    def cellz_rsrp_mean(csvlog_absfilepath):
        my_list = []
        csvfile_list = trans_absfilepath_to_filename(csvlog_absfilepath)
    # 1.异常情况预先处理
        if len(csvlog_absfilepath) == 0 or csvlog_absfilepath=="":
            print("你还没有通过点击“文件”选择待导入处理的文件目录!")
    # 2.读取csv文件到内存
        elif len(csvlog_absfilepath) >= 1:
            num = len(csvlog_absfilepath)
            for j in range(num):  #逐项遍历
                # 1、加载指定的csv文件数据列到内存,优化程序速度
                df = pd.read_csv(csvlog_absfilepath[j],encoding = 'utf-8',usecols=[0,11,20])  #读取csv文件到内存,读取指定的[0,11,20] 列
                # 2、根据实际的5G?4G?情况处理加载初始数据列
                b_SS_RSRP = df['SS-RSRP'].isnull().all()  # 判断SS-RSRP列是否全部为NaN
                b_RSRP = df['RSRP'].isnull().all()  # 判断RSRP列是否全部为NaN
                if b_RSRP==True and b_SS_RSRP==False:  #测试5G
                    df1 = df[["TIME","SS-RSRP"]] 
                elif b_RSRP==False and b_SS_RSRP==True:  #测试4G
                    df1 = df[["TIME","RSRP"]] 
                else:  #异常情况,需要打印提示
                    print("-----抓取cell_z缓存csv日志步骤出错,请先退出程序重试!-----")
                # 3、处理含有NaN的数据行
                df2 = df1.dropna(how="any")
                temp = df2.index
                dflen = len(temp)  #求出df对象的长度
                # 4、根据正则表达式提取
                pattern_1 = r"^\d{8}.*\d{2}:\d{2}:\d{2}"
                avg_index_list = []
                rsrp_list = []
                for i in range(dflen):
                    result_l = re.findall(pattern= pattern_1 , string= df2.iloc[i,0] )  # 索引值是从0开始,并且是去除了NaN的那个df对象,从新开始数的
                    avg_index_list.append( result_l[0] )
                    rsrp_list.append( df2.iloc[i,1] )
                # print(avg_index_list)  #获得1个由时间构成的列表,相当于Excel的用,文本分列    
                # print(rsrp_list)  #获得1个由信号强度构成的列表,相当于Excel的用,文本分列 
                # 5、使用zip()内置函数创建DataFrame
                zip_result = zip(avg_index_list,rsrp_list)
                zip_result_list = list(zip_result)
                df3 = pd.DataFrame(zip_result_list,columns=["时间","数值"])
                #  6、数据分组计算平均值
                _df_count = df3.groupby("时间").count()   #计数
                _df_mean = df3.groupby("时间").mean()  #平均值
                _df_mean_all = _df_mean["数值"].mean() #数据透视表求Cellular_Z.apk输出日志的RSRP真实平均值
                #  7、对浮点值进行小数点后7位处理化简
                _df_mean_all_round_7 = round( _df_mean_all ,7)
                _df_mean_all_round_4 = round( _df_mean_all ,4)
                # mydict.setdefault(csvlog_absfilepath[j],_df_mean_all_round_4)
                my_list.append((csvlog_absfilepath[j],csvfile_list[j],_df_mean_all_round_4))  #返回1个Tuple元祖,构成的list列表
            # print(my_list)   #调试时打印用,正式运行环境需要注释掉
        return my_list  #把结果放在列表里返回
    
    # 定义一个方法,将list数据结构输出到Excel文件里
    def write_list_into_excel(var = "list"):
        if var=="list" or len(var)==0:  # 如果未选择文件导入目录路径,则不输出Excel文件
            pass  # TODO
        else:
            df1 = pd.DataFrame(var,columns=["导入处理CSV文件的绝对路径","CSV文件名","实际信号平均值(dBm)"])
            excel_filename = os.getcwd()+"/"+"读取Cellular_Z日志输出信号透视平均值.xlsx"
            df1.to_excel(excel_writer = excel_filename )
            print("已输出Excel文件:{}".format('\t') + excel_filename )
            return excel_filename
    
    ###### 调试程序的主入口		
    if __name__ == "__main__":	
        test_csv_list = [r'D:/kang_log/test/report/LN78-2-D - 副本.CSV', r'D:\\kang_log\\test\\report\\Sn78-2-d - 副本.CSV']
        cellz_rsrp_mean(test_csv_list)
    

    CallReadCsvStringOutput.py

    查看代码
    
    # -*- coding: UTF-8 -*-
    
    """
        【简介】
        更新输出视图层文件的命令行
        pyuic5 -o ReadPdfStringOutput.py ReadPdfStringOutput.ui
        pyuic5 -o dialog_output_prompt.py dialog_output_prompt.ui
        更新前务必要先备份,因为业务逻辑写在上述2个.py文件里
        
    """
    
    import sys
    from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow, QWidget
    
    from ReadCsvStringOutputAvg import  Ui_MainWindowAresRT
    
    
    #  实例化程序的主界面
    class TurnplateWindowShow(QMainWindow, Ui_MainWindowAresRT): # Python多继承
        def __init__(self, parent=None):
            super( TurnplateWindowShow, self).__init__(parent)
            # self.setupUi(self)  # 调用写在视图层文件的页面布局方法
            self.initUI()
        
        def initUI(self):
            # 子类调用继承父类的方法
            super( TurnplateWindowShow, self).setupUi(self)   # 调用的父类方法 super().方法名()
    
    
    # 实例化输出结果文件的对话框
    # class OutputDialogShow(QDialog, Ui_Dialog): # Python多继承
    #     def __init__(self, parent=None):
    #         super( OutputDialogShow, self).__init__(parent)
    #         # self.setupUi(self)  # 调用写在视图层文件的页面布局函数
    #         self.initUI()
        
    #     def initUI(self):
    #         # 子类调用继承父类的方法
    #         super(OutputDialogShow, self).setupUi(self)   # 等价于参考书里的self.setupUi()
    
    # # 在业务层文件里定义主界面调用Dialog窗体函数
    # def show_d1():
    #     d1.show()  # OutputDialogShow的实例化对象d1
    
    
    
    ###### 调试程序的主入口		
    if __name__ == "__main__":	
        app = QApplication(sys.argv)
        w1 = TurnplateWindowShow()
        w1.show()  #主窗口
        # 调用界面d1对象的槽函数
        # w1.action_timer_setup.triggered.connect(show_d1) #槽函数只填写函数名不能带()
        sys.exit(app.exec_())
  • 相关阅读:
    pip相关工具使用小结
    PyCharm配置autopep8,自动格式化Python代码
    PyCharm运行Nosetests并导出测试报告
    Jenkins集成taffy进行自动化测试并输出测试报告
    Locust性能测试框架,从入门到精通
    浅谈如何打造一个安全稳定高效的容器云平台
    微服务治理平台的RPC方案实现
    这个需求我不接之事务的自动补偿
    微服务熔断隔离机制及注意事项
    容器化-Docker介绍
  • 原文地址:https://www.cnblogs.com/MarlonKang/p/16053612.html
Copyright © 2020-2023  润新知