如何查找d驱动器中所有文件夹使用的空间?

b1zrtrql  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(309)

我想跟踪d驱动器中所有文件夹的大小,以便在microsoft access中为其创建数据库。有人知道如何更好地用python编写代码吗?我在这里查看了类似的问题,但代码显示了驱动器中存在的单个文件夹的大小,但我希望它显示驱动器中存在的所有文件夹的大小。如果有人对此有任何想法,这将意味着很多。谢谢
(例如:如果我的d驱动器有4个文件夹,那么我希望它显示所有4个文件夹的大小;如果第二天我在驱动器中添加了一个额外的文件夹,那么当我运行代码时,我希望它现在显示所有5个文件夹的大小,这样我就可以为相同的文件夹创建数据库。)

import os
import math as m

current_wd = os.getcwd()

directory_location = "D:\Demofolder"
New_wd = os.chdir(directory_location)

current_wd = os.getcwd()

# print(current_wd)

# print(os.path.getsize(directory_location))

total_dir_size=0
for file in os.listdir():
 #   print(file)
  x =  os.path.getsize(directory_location + "/" + file)
  x_in_kb = x/1024
  total_dir_size += x_in_kb
 # print(x_in_kb)
 # 
print(str(m.trunc(total_dir_size))+ "kb")
kqlmhetl

kqlmhetl1#

你可以用 os.path.getsize(folder) 获取文件夹的大小。例如:

import os
def getFolderSize(folder):
    total_size = os.path.getsize(folder)
    try:
        for item in os.listdir(folder):
            itempath = os.path.join(folder, item)

            if os.path.isdir(itempath):
                total_size += getFolderSize(itempath)
            elif os.path.isfile(itempath):
                total_size += os.path.getsize(itempath)
    except Exception:
        print("ex")
    return total_size
a=os.listdir("D:\\")
for folder in a:
    if os.path.isdir("D:\\"+folder):
        print(getFolderSize("D:\\"+folder))

相关问题