天天看點

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檔案個數,以及所有檔案中的總記錄數。