| 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.") |
|
|
| |
| 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): |
| |
| 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.") |
|
|