Created
October 6, 2023 11:41
-
-
Save BlueSkyXN/28ff1eac18a8ca2670150da6dd800139 to your computer and use it in GitHub Desktop.
group_files.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import shutil | |
| import argparse | |
| #GPLv3 @BlueSkyXN | |
| def main(target_folder, files_per_group): | |
| print(f"目标文件夹:{target_folder}") | |
| print(f"每组文件数量:{files_per_group}") | |
| # 检查目标文件夹是否存在 | |
| if not os.path.exists(target_folder): | |
| print(f"错误:目标文件夹 {target_folder} 不存在。") | |
| return | |
| # 列出目标文件夹内的所有文件 | |
| all_files = [f for f in os.listdir(target_folder) if os.path.isfile(os.path.join(target_folder, f))] | |
| total_files = len(all_files) | |
| print(f"目标文件夹中的文件总数:{total_files}") | |
| # 计算需要分多少组 | |
| num_groups = total_files // files_per_group | |
| if total_files % files_per_group != 0: | |
| num_groups += 1 # 如果有余数,则需要多一个组 | |
| print(f"需要分成的组数:{num_groups}") | |
| # 创建新的分组文件夹并移动文件 | |
| current_group = 1 | |
| current_file_count = 0 | |
| for f in all_files: | |
| # 创建新的分组文件夹 | |
| if current_file_count == 0: | |
| group_folder = os.path.join(target_folder, f"{current_group:03d}") | |
| os.makedirs(group_folder, exist_ok=True) | |
| print(f"创建了新的分组文件夹:{group_folder}") | |
| # 移动文件到新的分组文件夹 | |
| shutil.move(os.path.join(target_folder, f), os.path.join(group_folder, f)) | |
| print(f"移动文件 {f} 到 {group_folder}") | |
| current_file_count += 1 | |
| # 如果当前组已满,移动到下一个组 | |
| if current_file_count >= files_per_group: | |
| current_file_count = 0 | |
| current_group += 1 | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description="将目标文件夹内的文件分组。") | |
| parser.add_argument("-p", "--path", type=str, required=True, help="目标文件夹的绝对路径") | |
| parser.add_argument("-n", "--num", type=int, required=True, help="每一组有多少文件") | |
| args = parser.parse_args() | |
| main(args.path, args.num) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment