python用递归实现计算一个文件夹下所有文件的大小(文件夹下还有文件夹)

递归实现:计算一个文件夹里面所有文件的大小


deftraverse(path):
   db= 0
   # 拿到p路径下所有文件和文件夹的名字
   fs= os.listdir(path)
   for f1 in fs:
       # 拼接路径和文件夹的名字,合成一个绝对路径
       next_path= os.path.join(path, f1)
       if not os.path.isdir(next_path):
           db += os.path.getsize(next_path)
       else:
           ret= traverse(next_path)  # 每调用一次会返回一个db
           db+= ret
   returndb
原文地址:https://www.cnblogs.com/he-qing-qing/p/10859123.html