码迷,mamicode.com
首页 > 编程语言 > 详细

python获取文件夹下数量

时间:2018-01-28 11:27:42      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:number   单位换算   获取   print   遍历   exist   erro   glob   direct   

import os

totalSize = 0
fileNum = 0
dirNum = 0


def visitDir(path):
    global totalSize
    global fileNum
    global dirNum
    for lists in os.listdir(path):
        sub_path = os.path.join(path, lists)
        print(sub_path)
        if os.path.isfile(sub_path):
            fileNum = fileNum+1                      # 统计文件数量
            totalSize = totalSize+os.path.getsize(sub_path)  # 文件总大小
        elif os.path.isdir(sub_path):
            dirNum = dirNum+1                       # 统计文件夹数量
            visitDir(sub_path)                           # 递归遍历子文件夹


def sizeConvert(size):                                   # 单位换算
    K, M, G = 1024, 1024**2, 1024**3
    if size >= G:
        return str(size/G)+‘G Bytes‘
    elif size >= M:
        return str(size/M)+‘M Bytes‘
    elif size >= K:
        return str(size/K)+‘K Bytes‘
    else:
        return str(size)+‘Bytes‘


def main(path):
    if not os.path.isdir(path):
        print(‘Error:"‘, path, ‘" is not a directory or does not exist.‘)
        return
    visitDir(path)

def output(path):
    print(‘The total size of ‘+path+‘ is:‘+sizeConvert(totalSize))
    print(‘The total number of files in ‘+path+‘ is:‘,fileNum)
    print(‘The total number of directories in ‘+path+‘ is:‘,dirNum)


if __name__ == ‘__main__‘:
    path = r‘E://Files‘
    main(path)
    output(path)

  

python获取文件夹下数量

标签:number   单位换算   获取   print   遍历   exist   erro   glob   direct   

原文地址:https://www.cnblogs.com/php-linux/p/8370513.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!