Python计算文件夹(压缩包)目录的大小以及将Python脚本打包为exe(Windows)

本文分为两部分:

1、自动化计算文件夹或zip压缩包下路径所占内存大小

2、将python脚本打包成Windows上的可执行文件(.exe)

1、计算文件夹或zip压缩包下路径所占内存大小:
(1)输入路径

if __name__ == '__main__':
    pathvar = input("输入需要计算的路径:\n")
    calculateSize(pathvar)
    pathOfResult = os.getcwd()
    pathOfResult += RESULT_PATH_.replace('.', "")
    pathOfResult = pathOfResult.replace('/', '\\') + ".xls"
    print("已将数据成功写入: " + pathOfResult)
    os.system('pause')

(2)分别计算zip包和普通路径

def calculateSize(pathvar):
    length = len(pathvar.split(".zip"))
    rootPath = pathvar.split(".zip")[0]
    print("正在解析路径内容...")
    if length > 1:
        rootPath = rootPath + ".zip"
        calculateSizeOfZip(rootPath)
    else:
        sizeMap = {}
        print("解析为正常路径...")
        calculateSizeOfDir(pathvar, sizeMap, pathvar)
        print("即将写入xls文件...")
        saveDataToXlsx(sizeMap)

(3)计算普通路径:

def calculateSizeOfDir(pathvar, sizeMap, rootDir):
    size = 0
    lst = os.listdir(pathvar)
    for i in lst:
        pathnew = os.path.join(pathvar, i)
        if os.path.isfile(pathnew):
            size += os.path.getsize(pathnew)
            subDir = pathvar.replace(rootDir, "")
            sizeList = []
            sizeList.append(size)
            sizeList.append(exchangeSize(size))
            sizeMap[subDir] = sizeList
        elif os.path.isdir(pathnew):
            calculateSizeOfDir(pathnew, sizeMap, rootDir)

(4)计算zip包:

def calculateDetailSizeOfZip(info, sizeInfoList):
    fileName = info.filename
    nameList = fileName.split("/")
    lengthOfPath = len(nameList) - 1
    for index, name in enumerate(nameList):
        if lengthOfPath == index and lengthOfPath > 1:
            break
        curName = ""
        for i in range(0, index):
            curName = curName + "/" + nameList[i]
        curName = curName + "/" + name
        if (len(sizeInfoList) <= index):
            dictOut = {}
            dictOut[curName] = {"size": 0, "compress_size": 0,
                                "size_unit": 0, "compress_size_unit": 0}
            sizeInfoList.append(dictOut)
        if curName not in sizeInfoList[index].keys():
            sizeInfoList[index][curName] = {"size": 0, "compress_size": 0,
                                "size_unit": 0, "compress_size_unit": 0}
        sizeInfoList[index][curName]["size"] += info.file_size
        sizeInfoList[index][curName]["compress_size"] += info.compress_size

(5)转换单位,方便阅读

def exchangeSize(oldSize):
    unitForSize = oldSize / 1024
    if unitForSize < 1:
        return str(oldSize) + "B"
    if unitForSize >= 1024:
        unitForSize = unitForSize / 1024
        unitForSize = round(unitForSize, 2)
        return str(unitForSize) + "MB"

    unitForSize = round(unitForSize, 2)
    return str(unitForSize) + "KB"

(6)显示进度,方便遇到问题时及时定位

def rateOfProgress(index, length, preStr):
    progressNums = (index / length) * 100
    progressNums = round(progressNums, 2)
    progressStr = str(progressNums) + '%'
    print(preStr + progressStr + " ...")

(7)将文件格式化后写入Excel文档中(.xls文件)

def saveZipInfoToXlsx(sizeInfoList, totalList):
    xls = xlwt.Workbook()
    sht1 = xls.add_sheet('Sheet1')
    listOfTatalTitle = ["total_size", "total_compress_size", "total_size_u", "total_compress_size_u"]
    for idn, title in enumerate(listOfTatalTitle):
        sht1.write(0, idn, title)
        sht1.write(1, idn, totalList[idn])

    beginIndex = len(listOfTatalTitle) + 1
    listOfTitle = ["path", "size", "compress_size", "size_u", "compress_size_u"]
    lengthOfTitle = len(listOfTitle)
    for info in sizeInfoList:
        for index, item in enumerate(listOfTitle):
            sht1.write(0, beginIndex + index, item)
        for index, nameKey in enumerate(info.keys()):
            sht1.write(index + 1, beginIndex, nameKey)
            subInfo = info[nameKey]
            for subIndex, value in enumerate(subInfo.values()):
                sht1.write(index + 1, beginIndex + subIndex + 1, value)
        beginIndex += (lengthOfTitle + 1)

    xls.save(RESULT_PATH_)
def saveDataToXlsx(dataMap):
    xls = xlwt.Workbook()
    sht1 = xls.add_sheet('Sheet1')
    listOfTitle = ["path", "size_native", "size"]
    for index, item in enumerate(listOfTitle):
        sht1.write(0, index, item)

    for index, curPath in enumerate(dataMap.keys()):
        sht1.write(index + 1, 0, curPath)
        sizeList = dataMap[curPath]
        for subIndex, item in enumerate(sizeList):
            sht1.write(index + 1, subIndex + 1, item)

    xls.save(RESULT_PATH_)

(8)运行即可得到结果

2、将python脚本打包成exe
(1)在脚本运行的python环境下安装pyinstaller
a.打开Windows PowerShell
b.进入python所在环境后,执行 python -m pip install pyinstaller
在这里插入图片描述
c.安装成功

(2)执行打包
a.执行命令:
其中-F是输出文件,如果有依赖的静态库,需要添加-p参数;
静态库存放在当前环境的\Lib\site-packages下

 .\pyinstaller.exe -F -p ..\Lib\site-packages  ..\..\main.py

b.执行完成后在\dist\文件夹下找到exe文件即可。

(3)遇到的问题:
出现PermissionError: [Errno 13] Permission denied: ‘C:\…dll
解决方案:
a.C:\Windows\System32下不存在.dll文件
下载api-ms-win-crt-runtime-l1-1-0.dll到电脑,然后拷贝该文件到C:\Windows\System32下。
下载地址:https://www.greenxf.com/soft/125654.html
b.该.dll被占用了,尝试推出一些杀毒软件或者重启
c.权限问题,以管理员身份打开Windows Powershell

你可能感兴趣的:(其他,办公,windows,python,pycharm)