700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Python获取指定目录下文件数量及总大小

Python获取指定目录下文件数量及总大小

时间:2020-03-11 07:17:58

相关推荐

Python获取指定目录下文件数量及总大小

欢迎大家访问我的网站:

import ostotalSize = 0fileNum = 0dirNum = 0def visitDir(path):global totalSizeglobal fileNumglobal dirNumfor 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**3if 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.')returnvisitDir(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)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。