viewing paste rename files python | Python

Posted on the
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
import os
import sys
 
def rename_files(prefix, directory):
    if not os.path.isdir(directory):
        print(f"Error: '{directory}' is not a valid directory.")
        return
    
    for filename in os.listdir(directory):
        old_path = os.path.join(directory, filename)
        if os.path.isfile(old_path):
            new_filename = f"{prefix}{filename}"
            new_path = os.path.join(directory, new_filename)
            os.rename(old_path, new_path)
            print(f"Renamed: {filename} -> {new_filename}")
 
if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python3 script.py <prefix> <directory>")
        sys.exit(1)
    
    prefix_arg = sys.argv[1]
    directory_arg = sys.argv[2]
    rename_files(prefix_arg, directory_arg)
 
Viewed 681 times, submitted by Streusel.