递归查询目录大小
1.查看目录下所有目录和文件
import json, os def list_dir(path, res): for i in os.listdir(path): temp_dir = os.path.join(path, i) if os.path.isdir(temp_dir): temp = {"dirname": temp_dir, 'child_dirs': [], 'files': []} res['child_dirs'].append(list_dir(temp_dir, temp)) else: res['files'].append(i) return res def get_config_dirs(): res = {'dirname': 'root', 'child_dirs': [], 'files': []} return list_dir(r'/opt/code/my_code/zk_css', res) if __name__ == '__main__': print(json.dumps(get_config_dirs()))
来源:http://lvmy.iteye.com/blog/1258824
2.查询目录下的所有文件的总大小
# -*- coding: utf-8 -*- """ __title__ = 'get_dir_size02.py' __author__ = 'yangyang' __mtime__ = '2018.01.19' """ import os def calc_dir_size(path,res_li): for i in os.listdir(path): temp_dir = os.path.join(path,i) if os.path.isdir(temp_dir): calc_dir_size(temp_dir,res_li) else: res_li += os.path.getsize(temp_dir) return res_li if __name__ == '__main__': dirname = r'D:\gitcode\oldboy_python_study\third_module\practice\ftp_upgraded_version\server\user_home\ryan' res_li = 0 return_res = calc_dir_size(dirname,res_li) print(return_res)