Python query folder size, file which contains subfolders.

#!/usr/local/python37/bin/python3
# coding:utf-8
import os
import sys

try:
    directory = sys.argv[1]                   # 接受用户指定的 目录地址
except IndexError:
    sys.exit("Must provide an argument.")     # 用户必须输入一个参数(地址)

dir_size = 0                                  # 初始化 目录大小
fsizedicr = {'Bytes': 1,
             'Kilobytes': float(1) / 1024,
             'Megabytes': float(1) / (1024 * 1024),
             'Gigabytes': float(1) / (1024 * 1024 * 1024)}

for (path,dirs,files) in os.walk(directory):  # os.walk 查一下就明白了<generator>
    for file in files:
        filename = os.path.join(path,file)
        dir_size += os.path.getsize(filename)

# 计算大小
fsizeList = [str(round(fsizedicr[key] * dir_size, 2)) + " " + key for key in fsizedicr]

if dir_size == 0:
    print ("File Empty")                      # 文件夹为空/指定文件大小为0
else:
    for units in sorted(fsizeList)[::-1]:     # 上面遍历字典生成的列表,
  											  # 字典无序,排序。
    # for units in fsizeList:
        print ("Folder Size: " + units)

Execute Python xxx.py / root / destination file path

Guess you like

Origin blog.csdn.net/sunt2018/article/details/90765037