""" rename_lower - Rename files to lowercase Usage: rename_lower FILE [FILE...] This script renames files by converting their filenames to lowercase. It performs validation to ensure files exist and that the target lowercase filename doesn't already exist before renaming. Examples: rename_lower MyFile.TXT rename_lower *.JPG rename_lower Document.PDF Image.PNG """ import sys from pathlib import Path def usage(): """Show usage information""" print("""Usage: ,rename_lower FILE [FILE...] Rename files to lowercase filenames. This script converts filenames to lowercase. It validates that files exist and checks for conflicts before renaming. Arguments: FILE One or more files to rename Options: -h, --help Show this help message Examples: ,rename_lower MyFile.TXT ,rename_lower *.JPG ,rename_lower Document.PDF Image.PNG Exit codes: 0 Success - all files renamed (or already lowercase) 1 Error - invalid arguments, missing files, or conflicts """) def rename_to_lowercase(filepath: str) -> bool: """ Rename a single file to lowercase. Arguments: filepath: Path to the file to rename Returns: True on success, False on error """ # Convert to Path object for easier manipulation original = Path(filepath) # Validate that the file exists if not original.exists(): print(f"Error: File not found: {filepath}", file=sys.stderr) return False # Get the directory and filename components directory = original.parent original_name = original.name lowercase_name = original_name.lower() # Check if the filename is already lowercase if original_name == lowercase_name: # Already lowercase, nothing to do return True # Construct the target path target = directory / lowercase_name # Check if target already exists if target.exists(): print(f"Error: Target file already exists: {target}", file=sys.stderr) print(f" Cannot rename: {filepath}", file=sys.stderr) return False # Perform the rename try: original.rename(target) print(f"Renamed: {original_name} -> {lowercase_name}") return True except OSError as e: print(f"Error: Failed to rename {filepath}: {e}", file=sys.stderr) return False def main(): """Main script logic""" # Handle help flag or no arguments if len(sys.argv) == 1 or sys.argv[1] in ("-h", "--help"): usage() return 0 if len(sys.argv) > 1 else 1 success = True # Process each file argument for filepath in sys.argv[1:]: if not rename_to_lowercase(filepath): success = False # Continue processing other files even if one fails return 0 if success else 1 if __name__ == "__main__": sys.exit(main())