python os 文件/目录方法
首先介绍用到的几个函数,写了一个小demo便于理解。
os.getcwd()
返回当前路径。
os.listdir (path)
返回当前路径下的文件夹与文件(不向下二级递归)。
os.path.join()
join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
os.path 让join()识别为路径,根据系统自动补齐” ‘/’。
os.path.getsize(path) 返回文件大小
# -*- encoding: utf-8 -*_import ospath = os.getcwd() # 获取当前路径for dirs in os.listdir(path): print dirsfile_name = "路径补齐.txt"path = os.path.join(path,file_name)print pathsize = os.path.getsize("E:PythonEclipsePythonStudyos.listdirlistdirs.py")print size
登录后复制
输出结果:
ABCfile.txtlistdirs.pyE:PythonEclipsePythonStudyos.listdir路径补齐.txtA303
登录后复制
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
top — 根目录下的每一个文件夹(包含它自己), 产生3-元组 (dirpath, dirnames, filenames)【文件夹路径, 文件夹名字, 文件名】。
topdown –可选,为True或者没有指定, 一个目录的的3-元组将比它的任何子文件夹的3-元组先产生 (目录自上而下)。如果topdown为 False, 一个目录的3-元组将比它的任何子文件夹的3-元组后产生 (目录自下而上)。
onerror — 可选,是一个函数; 它调用时有一个参数, 一个OSError实例。报告这错误后,继续walk,或者抛出exception终止walk。
followlinks — 设置为 true,则通过软链接访问目录。
# -*- encoding: utf-8 -*_import osfor root, dirs, filename in os.walk(os.getcwd()): print root print dirs print filename
登录后复制
输出结果:
E:PythonEclipsePythonStudyos.listdir['A', 'B', 'C']['file.txt', 'listdirs.py']E:PythonEclipsePythonStudyos.listdirA[][]E:PythonEclipsePythonStudyos.listdirB[]['file.txt']E:PythonEclipsePythonStudyos.listdirC[][]
登录后复制
功能实现思路:
需要获取文件夹的大小,只要遍历文件下所有的文件,获取所有文件大小求和即可。
这里是实现的是当前目录下,文件夹大小不包括当前文件下文件大小。
python的编码的格式,需要注意。
# -*- encoding: utf-8 -*-import osrootdir = os.getcwd() #获取当前路径rootdir = rootdir.decode('gbk')x = u'统计文件大小.csv'f = open(os.path.join(rootdir,x), "w+")for dirname in os.listdir(rootdir): #获取二级目录所有文件夹与文件 Dir = os.path.join(rootdir, dirname) #路径补齐 count = 0 if (os.path.isdir(Dir)): #判断是否为目录 for r, ds, files in os.walk(Dir): #遍历目录下所有文件根,目录下的每一个文件夹(包含它自己), 产生3-元组 (dirpath, dirnames, filenames)【文件夹路径, 文件夹名字, 文件名称】 for file in files: #遍历所有文件 size = os.path.getsize(os.path.join(r, file)) #获取文件大小 count += size if ((count/1024.0/1024.0) < 1024): print Dir +'' + '%.2f'% (count/1024.0/1024.0)+'MB' f.write(Dir.encode("gbk") +','+ '%.2f'% (count/1024.0/1024.0)+'MB' + '') else: print Dir + '' + '%.2f' % (count / 1024.0 / 1024.0/1024.0) + 'GB' f.write(Dir.encode("gbk") + ',' + '%.2f' % (count / 1024.0 / 1024.0/1024.0) + 'GB' + '') else: continuef.close()
登录后复制
更多Pyhon 获取文件夹的大小统计相关文章请关注PHP中文网!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2278615.html