获取指定文件夹的大小:
方法1:使用递归:
import os def getTotalSize(path): sumSize = 0 if os.path.isdir(path): dirList = os.listdir(path) for dir in dirList: if os.path.isdir(os.path.join(path, dir)): sumSize += getTotalSize(os.path.join(path, dir)) else: sumSize += os.path.getsize(os.path.join(path, dir)) return sumSize elif os.path.isfile(path): return os.path.getsize(path) else: print("not valid path")
方法2: 使用循环列表
import os def getTotalSizeByXH(path): if os.path.isdir(path): sumSize = 0 listdir = [os.path.join(path, dir) for dir in os.listdir(path)] print("listdir", listdir) while listdir: subDir = listdir.pop(-1) print("subDir", subDir) if os.path.isdir(subDir): listdir.extend([os.path.join(subDir, dir) for dir in os.listdir(subDir)]) else: sumSize+=os.path.getsize(subDir) return sumSize elif os.path.isfile(path): return os.path.getsize(path) else: print("%s, 该路径非法" %path)
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/273087.html