python3获取文件及文件夹大小

获取文件大小

os.path.getsize(file_path):file_path为文件路径

>>> import os
>>> os.path.getsize(‘d:/svn/bin/SciLexer.dll‘)
1479904

获取文件夹大小

遍历文件夹,将所有文件大小加和。遍历文件夹使用os.walk函数

import os
from os.path import join, getsize

def getdirsize(dir):
    size = 0
    for root, dirs, files in os.walk(dir):
        size += sum([getsize(join(root, name)) for name in files])
    return size

if __name__ == ‘__main__‘:
    size = getdirsize(r‘D:\svn‘)
    print(‘There are %.3f‘ % (size / 1024 / 1024), ‘Mbytes in D:\\svn‘)执行结果:
 

help(os.walk)获取帮助信息

Help on function walk in module os:

walk(top, topdown=True, onerror=None, followlinks=False)
    Directory tree generator.

    For each directory in the directory tree rooted at top (including top
    itself, but excluding ‘.‘ and ‘..‘), yields a 3-tuple

        dirpath, dirnames, filenames

    dirpath is a string, the path to the directory.  dirnames is a list of
    the names of the subdirectories in dirpath (excluding ‘.‘ and ‘..‘).
    filenames is a list of the names of the non-directory files in dirpath.
    Note that the names in the lists are just names, with no path components.
    To get a full path (which begins with top) to a file or directory in
    dirpath, do os.path.join(dirpath, name).

    If optional arg ‘topdown‘ is true or not specified, the triple for a
    directory is generated before the triples for any of its subdirectories
    (directories are generated top down).  If topdown is false, the triple
    for a directory is generated after the triples for all of its
    subdirectories (directories are generated bottom up).

    When topdown is true, the caller can modify the dirnames list in-place
    (e.g., via del or slice assignment), and walk will only recurse into the
    subdirectories whose names remain in dirnames; this can be used to prune the
    search, or to impose a specific order of visiting.  Modifying dirnames when
    topdown is false is ineffective, since the directories in dirnames have
    already been generated by the time dirnames itself is generated. No matter
    the value of topdown, the list of subdirectories is retrieved before the
    tuples for the directory and its subdirectories are generated.

    By default errors from the os.scandir() call are ignored.  If
    optional arg ‘onerror‘ is specified, it should be a function; it
    will be called with one argument, an OSError instance.  It can
    report the error to continue with the walk, or raise the exception
    to abort the walk.  Note that the filename is available as the
    filename attribute of the exception object.

    By default, os.walk does not follow symbolic links to subdirectories on
    systems that support them.  In order to get this functionality, set the
    optional argument ‘followlinks‘ to true.

    Caution:  if you pass a relative pathname for top, don‘t change the
    current working directory between resumptions of walk.  walk never
    changes the current directory, and assumes that the client doesn‘t
    either.

    Example:

    import os
    from os.path import join, getsize
    for root, dirs, files in os.walk(‘python/Lib/email‘):
        print(root, "consumes", end="")
        print(sum([getsize(join(root, name)) for name in files]), end="")
        print("bytes in", len(files), "non-directory files")
        if ‘CVS‘ in dirs:
            dirs.remove(‘CVS‘)  # don‘t visit CVS directories
时间: 2024-11-07 06:49:41

python3获取文件及文件夹大小的相关文章

python3获取文件目录和文件

import os,sys if __name__=="__main__": print("__file__ = %s" % __file__) #获取文件相对路径 print("sys.argv[0]) = %s" % sys.argv[0]) #获取文件的全路径加文件名 print("sys.path[0] = %s " % sys.path[0]) #获取文件的全路径 print("os.getcwd() = 

获取iOS文件夹大小

提供一种获取iOS文件夹大小的方法.没有使用对文件夹内的文件枚举与文件大小字节数的累加. NSURL *cacheDirectory = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMaskappropriateForURL:nil create:NO error:nil]; NSDictionary *attributes = [[NSFileManager def

Python---进阶---文件操作---获取文件夹下所有文件的数量和大小

一.####编写一个程序,统计当前目录下每个文件类型的文件数 ####思路: - 打开当前的文件夹 - 获取到当前文件夹下面所有的文件 - 处理我们当前的文件夹下面可能有文件夹的情况(也打印出来) - 做出统计 ------------------------------------- import os #获取到当前文件夹下面所有的文件all_files = os.listdir(os.curdir) #os.curdir 表示当前目录 curdir:currentdirectory type

iOS获取文件和文件夹大小

//通常用于删除缓存的时,计算缓存大小 //单个文件的大小 - (long long) fileSizeAtPath:(NSString*) filePath{ NSFileManager* manager = [NSFileManager defaultManager]; if ([manager fileExistsAtPath:filePath]){ return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];

Linux C++获取文件夹大小

项目中要计算指定文件夹的大小.百度查到这篇文章,https://my.oschina.net/Tsybius2014/blog/330628方法可行,运行正确. 拿到我们的项目中,却遇到一些问题:程序中一些读文件的代码,开始报异常,都不到文件.这些都是以前没有遇到过的问题.到底是什么情况呢?排查了好久,终于发现使用该文章提供的计算文件夹大小的函数(暂且叫做GetDirectorySize),其中有改变当前目录的代码: chdir(dir); 我们的项目是多线程的,一个线程调用GetDirecto

Windows Store App JavaScript 开发:获取文件和文件夹列表

在应用程序中有时可能需要获取用户库中的内容,以便执行相关的操作.如果要获取某个用户库中的内容,需要先获取到这个用户库,获得用户库可以通过Windows.Storage命名空间中的KnownFolders类的相应属性来实现,可用属性包括documentsLibrary(文档库).musicLibrary(音乐库)和videosLibrary(视频库)等.获取到用户库之后,就可以使用KnownFolders类中的getItemsAsync.getFilesAsync或getFoldersAsync函

清除缓存,,计算文件夹大小

#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // //    NSLog(@"缓存文件大小为%@",[NSString stringWithFormat:@"%0.2fM",[self folderSizeAtPath:[N

shell学习之查找当前目录下文件以及文件夹大小-'du'命令和'df'命令

经过前几天的磁盘写满的事件之后,发现自己对du这个命令完全不知道,所以下决心要学习一番. 我就当一盘搬运工吧,外网找到一个教程 'du'就是查找文件夹的大小 du Typing the above at the prompt gives you a list of directories that exist in the current directory along with their sizes. The last line of the output gives you the tot

Win10系列:JavaScript获取文件和文件夹列表

在应用程序中有时可能需要获取用户库中的内容,以便执行相关的操作.如果要获取某个用户库中的内容,需要先获取到这个用户库,获得用户库可以通过Windows.Storage命名空间中的KnownFolders类的相应属性来实现,可用属性包括documentsLibrary(文档库).musicLibrary(音乐库)和videosLibrary(视频库)等.获取到用户库之后,就可以使用KnownFolders类中的getItemsAsync.getFilesAsync或getFoldersAsync函