File size: 1,609 Bytes
efa83a7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | import os
import shutil
ROOT = "./"
MAX_FILES = 8000 # 每个子目录最多文件数
def split_directory(dirpath):
"""
将 dirpath 下的直接文件分成 part_xxx 子目录
"""
print(f"→ Splitting directory: {dirpath}")
files = [
f for f in os.listdir(dirpath)
if os.path.isfile(os.path.join(dirpath, f))
]
total = len(files)
print(f" Found {total} files.")
# 按 MAX_FILES 分块
for idx in range(0, total, MAX_FILES):
part = idx // MAX_FILES
subdir = os.path.join(dirpath, f"part_{part:03d}")
os.makedirs(subdir, exist_ok=True)
for filename in files[idx: idx + MAX_FILES]:
src = os.path.join(dirpath, filename)
dst = os.path.join(subdir, filename)
shutil.move(src, dst)
print(f" - Created {subdir}")
print(f"✔ Completed: {dirpath}\n")
def walk_and_process(root):
"""
递归遍历整个目录树,发现需要拆分的目录就拆分
"""
for dirpath, dirnames, filenames in os.walk(root):
# 过滤掉我们自己创建的 part_000/part_001 目录,避免再次处理
dirnames[:] = [d for d in dirnames if not d.startswith("part_")]
file_count = len([
f for f in filenames
if os.path.isfile(os.path.join(dirpath, f))
])
if file_count > 10000:
print(f"▶ Found big directory: {dirpath} ({file_count} files)")
split_directory(dirpath)
if __name__ == "__main__":
walk_and_process(ROOT)
print("🎉 All oversized directories processed.")
|