学的 os , os.path 模块对文件目录处理,顺便实战一下。
import os
def list_size(path):
res={}
for dirpath, dirnames, filenames in os.walk(path):
for name in filenames:
fullpath = os.path.join(dirpath, name)
size = round(os.path.getsize(fullpath))
if size>0:
res[fullpath] = round(size/1024/1024)
return sorted(res.items(), key = lambda d:d[1], reverse = True)
path = 'E:'
with open(os.path.join('E:', 'filesize.txt'),'w') as f:
for i in list_size(path):
f.write(i[0]+'t'+str(i[1])+'MB'+'n')
os.listdir 只能看当前目录的文件,子文件夹的就不管了,所以就需要 os.walk 的遍历了。虽然小,不过还是挺实用的程序。





近期评论