python_os_shutil_获取文件夹下所有文件的大小

# sys.argv练习
# 写一个python脚本,在cmd里执行:
 python xxx.py 用户名 密码 cp 文件路径 目的地址
 python xxx.py alex sb cp D:\python_22\day22\1.内容回顾.py D:\python_22\day21
 python xxx.py alex sb rm D:\python_22\day22
 python xxx.py alex sb rename D:\python_22\day22  D:\python_22\day23

# 使用walk来计算文件夹的总大小
 import os
 g = os.walk('D:\python_22')
 for i in g :
     path,dir_lst,name_lst = i
     print(path,name_lst)


# 遍历文件夹计算文件夹的总大小方法总结:

# 1- 递归:
# 获取文件名列表os.listdir(path),遍历文件名列表,获取文件路径os.path.join(path,name),获取文件大小os.path.getsize(abs_path)
import os
def show_file_size(path):
    total_size=0
    name_lst = os.listdir(path)
    for name in name_lst:
        abs_path = os.path.join(path,name)  # 获取文件路径
        if os.path.isfile(abs_path):  # 判断是否是文件
            total_size+=os.path.getsize(abs_path)
        elif os.path.isdir(abs_path): # 如果还是文件夹,递归
            # print("here--",abs_path)
            total_size+=show_file_size(abs_path)    # 递归,层层遍历文件夹找文件
    return total_size

total_size=show_file_size(r'C:\Users\12078\PycharmProjects\OldBoy\Day22')
print(total_size, "%.4f MB" % (total_size/1024/1024))

# 2- os.walk (os.walk()是一个生成器函数):
import os

g = os.walk(r'C:\Users\12078\PycharmProjects\OldBoy\Day22')
full_size=0
for i in g :  # os.walk()是一个生成器函数  i可以替换为:path,dir_lst,file_lst
    path,dir_lst,file_lst = i  # 解包
    # print(path,dir_lst,file_lst)
    # print(file_lst)  # 虽然返回的是两个list(因为有子文件夹)但可以一起遍历!
    for filename in file_lst:
        full_size+=os.path.getsize(os.path.join(path,filename))
print(full_size, "%.4f MB" % (full_size/1024/1024))


# 优化如下:
import os
g = os.walk(r'C:\Users\12078\PycharmProjects\OldBoy\Day22')
full_size = 0
for path, dirs_list, files_list in g:
    for file in files_list:
        fullname = os.path.join(path, file)
        full_size +=os.path.getsize(fullname)
print(full_size, "%.4f MB" % (full_size/1024/1024))
# 把里层的for循环写成迭代器,再用sum来替代 full_size += file_size :


import os
folder_path = r'C:\Users\12078\PycharmProjects\OldBoy\Day22'
full_size = sum(sum(os.path.getsize(os.path.join(parent, file)) for file in files) for parent, dirs, files in os.walk(folder_path))
print(full_size, "%.4f MB" % (full_size/1024/1024))
# 使用sum求和的时候会把生成器的所有元素生成出来,相当于使用了 for i in g



# 3- shutil模块:获取磁盘使用空间(注意是磁盘的空间,不是文件夹或文件的大小,即便给的路径参数是文件夹或文件的绝对地址,计算的也是路径所在磁盘的空间)
# total, used, free = shutil.disk_usage(".")  # 解包
# print("当前磁盘共: %iGB, 已使用: %iGB, 剩余: %iGB"%(total / 1073741824, used / 1073741824, free / 1073741824))
import shutil
total_size, used_size, free_size = shutil.disk_usage(r'C:\Users\12078\PycharmProjects\OldBoy\Day22')
print(total_size, "%.4f MB" % (total_size/1024/1024))


posted @ 2020-06-02 22:45  collin_pxy  阅读(317)  评论(0编辑  收藏  举报