#!python import os import shutil import argparse def combine_split_files(base_dir, subdir_prefix="subdir_"): """ Moves all files from subdirectories (whose names start with subdir_prefix) back to the base directory. Args: base_dir (str): Path to the base directory containing split subdirectories. subdir_prefix (str): Prefix used for subdirectories created during split. Default is "subdir_". """ # List items in the base directory items = os.listdir(base_dir) combined_count = 0 for item in items: sub_dir_path = os.path.join(base_dir, item) # Process only directories with the given prefix if os.path.isdir(sub_dir_path) and item.startswith(subdir_prefix): print(f"Processing directory: {sub_dir_path}") for file_name in os.listdir(sub_dir_path): src_file = os.path.join(sub_dir_path, file_name) dst_file = os.path.join(base_dir, file_name) # If a file with the same name already exists, handle it (here we skip) if os.path.exists(dst_file): print(f"Warning: {dst_file} already exists. Skipping {src_file}.") continue try: shutil.move(src_file, dst_file) combined_count += 1 except Exception as e: print(f"Error moving {src_file} to {dst_file}: {e}") # After moving, attempt to remove the now-empty subdirectory try: os.rmdir(sub_dir_path) print(f"Removed directory: {sub_dir_path}") except Exception as e: print(f"Could not remove directory {sub_dir_path}: {e}") print(f"\nCombined {combined_count} files into {base_dir}.") def main(): parser = argparse.ArgumentParser( description="Rollback split files by moving files from split subdirectories back into the base directory." ) parser.add_argument("base_dir", help="Base directory containing the split subdirectories") parser.add_argument( "--prefix", default="subdir_", help="Prefix of the split subdirectories (default: 'subdir_')" ) args = parser.parse_args() # Validate the base directory exists if not os.path.isdir(args.base_dir): print(f"Error: {args.base_dir} is not a valid directory.") return combine_split_files(args.base_dir, args.prefix) if __name__ == "__main__": main()