第一个python小工具之文件分类处理

写博客除了分享交流技术,也有一点记录自己的生活、状态、感想的作用!今天上班上午学安卓开发,下午开会到4点,然后接了一下需求,做一个小工具;写完20点了,眼睛有点受不了。
好了,不多BB了。此小工具是根据文件名对文件进行分类处理,最后将统计结果写入excel表格。
代码

import os
import xlsxwriter
import re

def getJobNum(path):
    lists=[]
    for fileName in os.listdir(path):
        s=fileName[0:7]
        lists.append(s)
    formatList = list(set(lists))
    return formatList

def getNumByTag(searchWords,path):
    nums = []
    for i in range(len(searchWords)):
        num = 0
        for fileName in os.listdir(path):
            # if searchWords[i] in fileName:
            #     num+=1
            if (re.match(searchWords[i],fileName,0)) != None:
                num += 1
        nums.append(num)
    return nums

def writeToExcel(list1,list2,excelPath):
    # if not os.path.exists(excelPath):
    #     os.makedirs(excelPath)
    wb = xlsxwriter.Workbook(excelPath)
    ws=wb.add_worksheet()
    ws.write('A1','工号')
    ws.write('B1','数量')
    for i in range(len(list1)):
        ws.write('A'+str(i+2),list1[i])
        ws.write('B'+str(i+2),list2[i])
    wb.close()

if __name__ =='__main__':
    path= 'D:/download/test/'   #统计目标的文件
    nums = getNumByTag(getJobNum(path),path)
    writeToExcel(getJobNum(path),nums,'D:/download/test/test.xlsx')
    print('统计完成!')

    '''
                          使用说明
    
    getJobNum(path):
    读取文件下要统计的工号并返回列表
    
    getNumByTag(searchWords,path)  
    searchWords:要统计的关键字列表  path:统计的目标的文件夹
    
    writeToExcel(list1,list2,excelPath):
    excelPath:excel文件全路径,文件可以不存在,但文件路径必须存在,
    如上“D:/download/test/”必须存在,test.xlsx文件可以不存在;若存在则会覆盖,注意该文件名不要以统计的关键字开头
    '''
发布了12 篇原创文章 · 获赞 43 · 访问量 5435

猜你喜欢

转载自blog.csdn.net/weixin_40481076/article/details/101559935