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()

實際運行效果:

 

 同時在統計的目錄(文件夾)中會生成一個統計的文件,非常方便以后查看。

 

查看統計文件:

這里統計了輸入目錄中所有Excel文件,以及每個文件中的數據量。最后統計了所有Excel文件個數,以及所有文件中的總記錄數。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM