| import os | |
| import shutil | |
| def organize_directory(path): | |
| """ | |
| Organizes files in a directory into subdirectories based on the first 3 characters of the filename. | |
| """ | |
| print(f"Organizing files in: {path}") | |
| if not os.path.isdir(path): | |
| print(f"Error: Directory not found at {path}") | |
| return | |
| for filename in os.listdir(path): | |
| file_path = os.path.join(path, filename) | |
| if os.path.isfile(file_path): | |
| # Create subdirectory based on the first 3 characters | |
| subdir_name = filename[:3] | |
| subdir_path = os.path.join(path, subdir_name) | |
| if not os.path.exists(subdir_path): | |
| os.makedirs(subdir_path) | |
| print(f"Created directory: {subdir_path}") | |
| # Move the file | |
| new_file_path = os.path.join(subdir_path, filename) | |
| shutil.move(file_path, new_file_path) | |
| print(f"Moved: {file_path} -> {new_file_path}") | |
| if __name__ == "__main__": | |
| organize_directory('train') | |
| organize_directory('test') | |
| print("File organization complete.") |