您的位置:首页 > 编程语言 > Python开发

python遍历文件夹——两种遍历本地文件记录文件夹个数、文件数及文件大小的方法

2014-01-03 15:27 971 查看
这两个函数的功能:得到给定目录的文件夹个数、文件数,以及文件大小

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 遍历 递归