python基础 -- os模块
作者:互联网
获取指定文件夹的大小:
方法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)
标签:listdir,python,--,subDir,sumSize,path,os,dir 来源: https://www.cnblogs.com/lhg37927/p/16460544.html