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)
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)+ '('+ str(totalSize) +' Bytes)')
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'C:\python27'
main(path)
output(path)
python编写程序,统计指定文件夹大小以及文件和子文件夹数量。
最新推荐文章于 2022-03-21 11:47:10 发布