第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > python遍历文件夹下所有文件大小_python遍历文件夹——两种遍历本地文件记录文件夹个

python遍历文件夹下所有文件大小_python遍历文件夹——两种遍历本地文件记录文件夹个

时间:2018-08-17 07:59:22

相关推荐

python遍历文件夹下所有文件大小_python遍历文件夹——两种遍历本地文件记录文件夹个

这两个函数的功能:得到给定目录的文件夹个数、文件数,以及文件大小

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,οnerrοr=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遍历文件夹——两种遍历本地文件记录文件夹个数 文件数及文件大小的方法...

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。