python遍历文件夹——两种遍历本地文件记录文件夹个数、文件数及文件大小的方法
2014-01-03 15:27
971 查看
这两个函数的功能:得到给定目录的文件夹个数、文件数,以及文件大小
walkFolders函数没有用到os.walk函数,是自己递归调用的;walkfunc函数用到了os.walk函数,方便了很多。
walkFolders函数没有用到os.walk函数,是自己递归调用的;walkfunc函数用到了os.walk函数,方便了很多。
import os from os.path import join,getsize #没有使用os.walk函数 def walkFolders(folder): folderscount=0 filescount=0 size=0 folders=os.listdir(folder) #os.listdir(dirname):列出dirname下的目录和文件 for item in folders: path=os.path.join(folder,item) #os.path.join(path,name):连接目录与文件名或目录 if os.path.isdir(path): #os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false folderscount+=walkFolders(path)[0]+1 filescount+=walkFolders(path)[1] size+=walkFolders(path)[2] elif os.path.isfile(path): #os.path.isfile(name):判断name是不是一个文件,不存在name也返回false filescount+=1 size+=getsize(path) #os.path.getsize(filename):获取filename的文件大小, 单位为字节 return folderscount,filescount,size #使用了os.walk函数 def walkfunc(folder): folderscount=0 filescount=0 size=0 #walk(top,topdown=True,onerror=None) #top表示需要遍历的目录树的路径 #topdown的默认值是"True",表示首先返回目录树下的文件,然后在遍历目录树的子目录 #参数onerror的默认值是"None",表示忽略文件遍历时产生的错误.如果不为空,则提供一个自定义函数提示错误信息后继续遍历或抛出异常中止遍历 for root,dirs,files in os.walk(folder): #返回一个三元组:当前遍历的路径名,当前遍历路径下的目录列表,当前遍历路径下的文件列表 folderscount+=len(dirs) filescount+=len(files) size+=sum([getsize(join(root,name)) for name in files]) return folderscount,filescount,size if __name__ == '__main__': folder=os.getcwd() #os.getcwd():获得当前工作目录 folderscount,filescount,size=walkFolders(folder) print folder,folderscount,filescount,size folderscount,filescount,size=walkfunc(folder) print folder,folderscount,filescount,size
相关文章推荐
- python遍历文件夹读取文件大小
- Python遍历文件夹,删除空文件夹,过滤特定大小和格式的文件
- Python中文件遍历的两种方法
- Python遍历文件夹的两种方法比较
- python遍历文件夹,并进行文件读取的方法
- Python中文件遍历的两种方法
- Python遍历指定文件及文件夹的方法
- 在VC环境下遍历文件夹中的文件:两种方法
- Python遍历文件夹的两种方法比较
- Python遍历文件夹的两种方法比较
- Python遍历文件夹的两种方法比较
- Python遍历目录文件的两种方法
- Python遍历文件夹和读写文件的方法
- Python遍历文件夹和读写文件的方法
- Python批量重命名指定文件夹下文件的两种方法
- 对指定文件夹进行递归遍历,将所有文件存到QStringList里。两种方法
- Python遍历文件夹和读写文件的实现方法
- Python遍历文件夹和读写文件的方法
- python遍历文件夹找出文件夹后缀为py的文件方法
- Python遍历文件夹和读写文件的方法