天天看点

Python-统计目录(文件夹)中Excel文件个数和数据量

  背景:前一阵子在帮客户做Excel文件中的数据处理,但是每周提交周报,领导都需要统计从客户接收的文件数量以及记录数。所以我就简单写了统计的脚本,方便统计目录(文件夹)中的Excel文件个数和数据量。

  本人向来讲究直接利落,其他不多说,直接上代码。水平有限,仅供参考。

#!/usr/bin/env python
# coding:utf-8 
"""
@File Name: zwc_count_file.py
@Version: 1.0
@Python Version:  3.7
@Author: liguanbin
@Created Time: 2021/6/18 15:10
@Software: PyCharm
@Desc: 
"""

import os
import xlrd
import time

global file_list
file_list = []


def count_filenum():

    input_path = input("请输入目录:")

    if not input_path.endswith('\\'):
        input_path = input_path + "\\"
    else:
        input_path = input_path

    start_time = time.strftime("%Y%m%d%H%M%S", time.localtime())
    log_file = os.path.join(input_path,"文件统计_"+start_time[0:8]+".txt")

    for parent, dirtory, files in os.walk(input_path):
        for file in files:
            if file.endswith("xlsx") or file.endswith("xls"):
                file_path = os.path.join(parent,file)
                file_list.append(file_path)

    write_file(log_file, "【统计目录】:" + input_path)
    write_file(log_file, "-" * 100)

    all_num = 0
    for excel in file_list:
        fh = xlrd.open_workbook(excel)
        # 打开文件
        sheet = fh.sheet_by_index(0)
        num = sheet.nrows
        all_num += num
        # 将每个文件的记录数下入文件
        line_string = excel[len(input_path):len(excel)] + " : " + str(num)
        write_file(log_file,line_string)

    write_file(log_file, '-' * 100)
    write_file(log_file, "【目录中的总文件数】:" + str(len(file_list)))
    write_file(log_file, "【所有文件的总记录数】:" + str(all_num))
    write_file(log_file, '*' * 100)


def write_file(filename,content):
    file=open(filename,'a',encoding='utf-8')            #以追加方式打开日志文件
    print(content)                                      #控制台打印日志
    file.writelines(content+'\n')                       #写入内容
    file.close()


if __name__ == '__main__':

    count_filenum()      

实际运行效果:

Python-统计目录(文件夹)中Excel文件个数和数据量

 同时在统计的目录(文件夹)中会生成一个统计的文件,非常方便以后查看。

Python-统计目录(文件夹)中Excel文件个数和数据量

查看统计文件:

Python-统计目录(文件夹)中Excel文件个数和数据量

这里统计了输入目录中所有Excel文件,以及每个文件中的数据量。最后统计了所有Excel文件个数,以及所有文件中的总记录数。