第一种情况:如果G:\shangchang大小小于3gb(含等于3gb),则新建G:\shangchang1文件夹,将G:\shangchang的所有文件移动到G:\shangchang1文件夹中。
第二种情况:如果G:\shangchang大小大于3gb(不含等于3gb),则将G:\shangchang中当前根目录的文件或一级子目录随机组合(组合可以是若干个随机文件的组合、若干个随机文件和若干个文件夹的组合、若干个随机文件夹的组合,注意若干个是大于等于0的整数),只要随机组合的大小大于3gb且小于4.9gb,就新建命名规则为G:\shangchang1、G:\shangchang2、………等文件夹,将上述随机组合移动到新建的上述的文件夹中。
目前的代码:
import os
import shutil
import random
from pathlib import Path
def get_dir_size(dir_path: Path) ->
int
:
total = 0
[color=]
for entry in dir_path.iterdir():
if entry.is_file():
total += entry.stat().st_size
elif entry.is_dir():
total += get_dir_size(entry)
return total
def random_combination(dir_path: Path, min_size:
int
, max_size:
int
):
files = [f for f in dir_path.iterdir() if f.is_file()]
dirs = [d for d in dir_path.iterdir() if d.is_dir()]
# Randomly choose files and/or directories until the combination size meets the criteria
current_size = 0
[color=]
combination = []
while current_size or (max_size is not None and current_size > max_size):
if files and random.random() # Randomly choose to add a file or directory
file_or_dir = random.choice(files + dirs)
current_size += file_or_dir.stat().st_size
combination.append(file_or_dir)
if
isinstance
(file_or_dir, Path) and file_or_dir.is_file():
files.remove(file_or_dir) # Remove the selected file to avoid duplicates
elif
isinstance
(file_or_dir, Path) and file_or_dir.is_dir():
dirs.remove(file_or_dir)
else:
break
return combination
def split_directory(dir_path: Path, target_dir_name:
str
, min_size:
int
, max_size:
int
):
base_dir = Path(dir_path.parent, target_dir_name)
# If the original directory size is greater than or equal to 3GB, create multiple subdirectories and randomly distribute files
if get_dir_size(dir_path) >= min_size *
[color=]1024
**
[color=]3
:
i = 1
[color=]
total_size = get_dir_size(dir_path)
while total_size >= min_size *
[color=]1024
**
[color=]3
:
sub_dir = base_dir / f"{target_dir_name}{i}"
sub_dir.mkdir(
exist_ok
=True)
# Get a random combination and move it to the new subdirectory
combination = random_combination(dir_path, min_size *
[color=]1024
**
[color=]3
, max_size *
[color=]1024
**
[color=]3
)
for item in combination:
if item.is_file() and not item.parent == dir_path: # Skip files that are already in subdirectories
continue
dest_item = sub_dir / item.name
if dest_item.exists(): # Skip the item if it already exists in the destination
(f"Skipping {item} because it already exists in {sub_dir}")
continue
shutil.move(
str
(item),
str
(sub_dir))
# Update the total remaining size after moving items
total_size -=
sum
([entry.stat().st_size for entry in combination if entry.is_file()])
i += 1
if __name__ == "__main__":
source_dir = Path("G:/shangchang")
target_dir_name = "shangchang"
min_size_gb = 3
[color=]
max_size_gb = 4.9
[color=]
split_directory(source_dir, target_dir_name, min_size_gb, max_size_gb)经测试上面的代码不符合要求。