做某项目时,需要获取文件夹大小,磁盘的存储信息。通过学习整理了下,仅供参考。
def get_size(path):
list1 = []
fileList = os.listdir(path) # 获取path目录下所有文件
for filename in fileList:
pathTmp = os.path.join(path,filename) # 获取path与filename组合后的路径
if os.path.isdir(pathTmp): # 判断是否为目录
get_size(pathTmp) # 是目录就继续递归查找
elif os.path.isfile(pathTmp): # 判断是否为文件
filesize = os.path.getsize(pathTmp) # 如果是文件,则获取相应文件的大小
#print('目录中的子文件大小:%d字节' % filesize)
list1.append(filesize) # 将文件的大小添加到列表
print('%s 目录中的文件总大小:%d 字节' % (path, sum(list1)))
print('%s 目录中的文件总大小: %.4f MB' % (path, (sum(list1)/1024/1024)))
print('%s 目录中的文件总大小: %.4f GB' % (path, (sum(list1)/1024/1024/1024)))
path = "D:\\image"
get_size(path)
def get_disk_info():
disk_used = {}
for id in psutil.disk_partitions():
if 'cdrom' in id.opts or id.fstype == '':
continue
disk_name = id.device.split(':')
s = disk_name[0]
disk_info = psutil.disk_usage(id.device)
#print(disk_info)
disk_used[s + '盘使用率:'] = '{}%'.format(disk_info.percent)
disk_used[s + '剩余空间:'] = '{}GB'.format(disk_info.free // 1024 // 1024 // 1024)
print("sdsds:%s"%disk_used)
get_disk_info()
"""
Author:NoamaNelson
Date:2019-11-19
Discription:Get the size of D:\\image, and then this folder will keep writing files.
When the remaining space of D disk is less than 5GB, a warning message will be given
"""
import os
import os.path
import smtplib
import email.mime.multipart
import email.mime.text
import sendmail
import psutil
import collections
def get_size(path):
list1 = []
fileList = os.listdir(path) # 获取path目录下所有文件
for filename in fileList:
pathTmp = os.path.join(path,filename) # 获取path与filename组合后的路径
if os.path.isdir(pathTmp): # 判断是否为目录
get_size(pathTmp) # 是目录就继续递归查找
elif os.path.isfile(pathTmp): # 判断是否为文件
filesize = os.path.getsize(pathTmp) # 如果是文件,则获取相应文件的大小
#print('目录中的子文件大小:%d字节' % filesize)
list1.append(filesize) # 将文件的大小添加到列表
print('%s 目录中的文件总大小:%d 字节' % (path, sum(list1)))
print('%s 目录中的文件总大小: %.4f MB' % (path, (sum(list1)/1024/1024)))
print('%s 目录中的文件总大小: %.4f GB' % (path, (sum(list1)/1024/1024/1024)))
return sum(list1)
def get_disk_info():
disk_used = {}
for id in psutil.disk_partitions():
if 'cdrom' in id.opts or id.fstype == '':
continue
disk_name = id.device.split(':')
s = disk_name[0]
disk_info = psutil.disk_usage(id.device)
#print(disk_info)
disk_used[s + '盘使用率:'] = '{}%'.format(disk_info.percent)
disk_used[s + '剩余空间:'] = '{}GB'.format(disk_info.free // 1024 // 1024 // 1024)
print("sdsds:%s"%disk_used)
return disk_used
if __name__ == "__main__":
#path= input("请输入路径:").strip() #指定文件路径
path = r"D:\\image"
#intlist1 = get_size(path)
get_size(path)
disk_used1 = get_disk_info()
disk_used2 = disk_used1['D剩余空间:']
disk_used3 = int(disk_used2.split('G')[0])
#intlist2 = intlist1/1024/1024/1024
if disk_used3 > 5:
print("D剩余空间:%s"%disk_used1['D剩余空间:'])
elif disk_used3 <= 5:
mtxt = "D盘剩余空间为%dGB,建议停止数据存储"%disk_used3
print(mtxt)