python项目5-扫描当前目录和所有子目录并显示大小

import os
import sys

try:
    directory = sys.argv[1]  #Sys.argv[ ]其实就是一个列表,里边的项为用户输入的参数,关键就是要明白这参数是从程序外部输入的,而非代码本身的什么地方,要想看到它的效果就应该 将程序保存了,从外部来运行程序并给出参数
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)}
#os.walk()用于通过在目录树中游走输出在目录中的文件名,向上或者向下
for (path, dirs, files) in os.walk(directory):  # Walk through all the directories. For each iteration, os.walk returns the folders, subfolders and files in the dir.
    for file in files:  # Get all the files
        filename = os.path.join(path, file)
        dir_size += os.path.getsize(filename)  # 获取指定路径 path 下的文件的总大小,以字节(Byte)为单位

#round()返回浮点数x的四舍五入值
fsizeList = [str(round(fsizedicr[key] * dir_size, 2)) + " " + key for key in fsizedicr]

if dir_size == 0:
    print("File Empty")
else:
    for units in sorted(fsizeList)[::-1]:  # 对单位列表进行反向排序,以便于打印最小单位
        print("Folder Size: " + units)

在parameter中输入test可以得到test目录及其子目录的总共大小

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qtayu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值