搜索
首页后端开发Python教程Pyhon 获取文件夹的大小统计

Python OS 文件/目录方法

首先介绍用到的几个函数,写了一个小demo便于理解。

 Pyhon 获取文件夹的大小统计

os.getcwd()

返回当前路径。 

os.listdir (path)

返回当前路径下的文件夹与文件(不向下二级递归)。

os.path.join()

join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

os.path 让join()识别为路径,根据系统自动补齐'\' '/'。

os.path.getsize(path)  返回文件大小

# -*- encoding: utf-8  -*_
import os

path = os.getcwd() # 获取当前路径
for dirs in os.listdir(path):
    print dirs

file_name = "路径补齐.txt"
path = os.path.join(path,file_name)
print path
size = os.path.getsize("E:\PythonEclipse\PythonStudy\os.listdir\listdirs.py")
print size

输出结果:

A
B
C
file.txt
listdirs.py
E:\PythonEclipse\PythonStudy\os.listdir\路径补齐.txtA
303

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 os

for root, dirs, filename in os.walk(os.getcwd()):
    print root
    print dirs
    print filename

输出结果:

E:\PythonEclipse\PythonStudy\os.listdir
['A', 'B', 'C']
['file.txt', 'listdirs.py']
E:\PythonEclipse\PythonStudy\os.listdir\A
[]
[]
E:\PythonEclipse\PythonStudy\os.listdir\B
[]
['file.txt']
E:\PythonEclipse\PythonStudy\os.listdir\C
[]
[]

功能实现思路:

需要获取文件夹的大小,只要遍历文件下所有的文件,获取所有文件大小求和即可。

这里是实现的是当前目录下,文件夹大小不包括当前文件下文件大小。

python的编码的格式,需要注意。

# -*- encoding: utf-8 -*-
import os
rootdir = 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 +'\t' + '%.2f'% (count/1024.0/1024.0)+'MB'
            f.write(Dir.encode("gbk") +','+  '%.2f'% (count/1024.0/1024.0)+'MB' + '\n')
        else:
            print  Dir + '\t' + '%.2f' % (count / 1024.0 / 1024.0/1024.0) + 'GB'
            f.write(Dir.encode("gbk") + ',' + '%.2f' % (count / 1024.0 / 1024.0/1024.0) + 'GB' + '\n')
    else:
        continue
f.close()

更多Pyhon 获取文件夹的大小统计相关文章请关注PHP中文网!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解释吗?揭穿神话Python:它是真正的解释吗?揭穿神话May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

与同一元素的Python串联列表与同一元素的Python串联列表May 11, 2025 am 12:08 AM

concateNateListsinpythonwithTheSamelements,使用:1)operatototakeepduplicates,2)asettoremavelemavphicates,or3)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

解释与编译语言:Python的位置解释与编译语言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允许ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循环时:您什么时候在Python中使用?循环时:您什么时候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!