python读取文件大小_Python-读取文件的大小

1.python读取文件以及文件夹的大小

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

importos

os.path.getsize('d:/svn/bin/SciLexer.dll')#1479904

2. 遍历文件夹,将所有文件大小加和, os.walk()遍历文件夹

importosfrom os.path importjoin, getsizedefgetdirsize(dir):

size=0for root, dirs, files inos.walk(dir):

size+= sum([getsize(join(root, name)) for name infiles])return size

2.将文件大小进行格式化

defsize_format(size):if size < 1000:return '%i' % size + 'size'

elif 1000 <= size < 1000000:return '%.1f' % float(size/1000) + 'KB'

elif 1000000 <= size < 1000000000:return '%.1f' % float(size/1000000) + 'MB'

elif 1000000000 <= size < 1000000000000:return '%.1f' % float(size/1000000000) + 'GB'

elif 1000000000000 <=size:return '%.1f' % float(size/1000000000000) + 'TB'

你可能感兴趣的:(python读取文件大小)