计算任意文件夹的大小

# ### 计算任意文件夹的大小

import os
'''
pathvar = "/mnt/hgfs/gongxiang_16/day17/ceshi100"
lst = os.listdir(pathvar)
print(lst)


# 遍历所有的文件和文件夹,计算文件的大小
size = 0
for i in lst:
	# print(i)
	path_new = os.path.join(pathvar,i)
	# print(path_new)
	if os.path.isdir(path_new):
		print(i,"是一个[目录]")
	elif os.path.isfile(path_new):
		print(i,"是一个[文件]")
		size += os.path.getsize(path_new)
print(size) # 2132 + 97 = 2229
'''

# 使用递归来完成文件夹大小的计算
pathvar = "/mnt/hgfs/jiadiannao/ceshi010"
def getallsize(pathvar):
	size = 0
	lst  =os.listdir(pathvar)
	print(lst)
	for i in lst:
		print(i)
		# 拼接路径 + 文件名 => 新路径
		path_new = os.path.join(pathvar,i)
		if os.path.isdir(path_new):
			size += getallsize(path_new)
			'''
			size = size + getallsize(path_new)
			size = 2229 + getallsize(path_new)
			'''
		elif os.path.isfile(path_new):
			size += os.path.getsize(path_new)
	
	return size
res = getallsize(pathvar)
# print(res)

# x   2229 + 1272 + 1283  =   4784

  

转载于:https://www.cnblogs.com/huangjiangyong/p/10920521.html

你可能感兴趣的:(计算任意文件夹的大小)