文件夹里面不能包含文件夹
如果处理'D:\xxxxx',那么生成的文件夹在D:\而且文件夹名称Subfolder_1、2、3..........
[Python] 纯文本查看 复制代码 import os
import shutil
# 获取文件夹总大小、文件数量、单个文件大小
def get_folder_info(folder):
total_size = 0
file_count = 0
files_with_size = {}
for dirpath, dirnames, filenames in os.walk(folder):
for f in filenames:
fp = os.path.join(dirpath, f)
if os.path.isfile(fp):
file_size = os.path.getsize(fp)
files_with_size[f] = file_size
total_size += file_size
file_count += 1
return total_size, file_count, files_with_size
# 分配文件
def new_files(path,total_capacity):
count=0
# path父级目录
parent_folder = os.path.dirname(path)
while True:
print(f'开始分组,当前第:{count+1}组')
data=0
l=0
lod_files=get_folder_info(path)
if int(lod_files[1])>0:
subfolder_name = os.path.join(parent_folder, f"Subfolder_{count}")
os.makedirs(subfolder_name, exist_ok=True)
sorted_files = sorted(lod_files[2].items(), key=lambda x: x[1], reverse=True)
for name,file_size in sorted_files:
l+=1
file_path = os.path.join(path, name)
data+=file_size
if data//( 1024 * 1024 * 1024)>total_capacity:
break
shutil.move(file_path,subfolder_name)
if l >10:
break
count+=1
else:
break
if __name__ == "__main__":
# 你要处理的路径
path=r'D:\xxxxx'
# 文件夹最大大小,单位GB
total_capacity=20
# 获取处理文件夹的信息
lod_files=get_folder_info(path)
print(f'当前操作文件夹路径:{path}')
print(f"当前文件夹总大小:{lod_files[0]//(1024 * 1024)} MB")
print(f'当前操作文件夹文件数量:{lod_files[1]}')
# print(f'当前操作文件夹文件详细信息:{lod_files[2]}')
# 进行分离
new_files(path)
|