CaiusNelson

Python - Added suffex/prefex to filetype

Oct 28th, 2023
964
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. import os
  2.  
  3. def main():
  4.     # Get user input for the file extension, prefix, and suffix
  5.     file_ext = input("Enter the file extension type: ").strip().lower()
  6.     prefix = input("Enter the prefix string: ")
  7.     suffix = input("Enter the suffix string: ")
  8.  
  9.     # Ensure the file extension does not start with a dot
  10.     if not file_ext.startswith('.'):
  11.         file_ext = '.' + file_ext
  12.  
  13.     # Get the current directory
  14.     current_directory = os.path.dirname(os.path.realpath(__file__))
  15.  
  16.     # Loop through every file in the directory
  17.     edited_files = []
  18.     for filename in os.listdir(current_directory):
  19.         # If the file has the desired extension
  20.         if filename.lower().endswith(file_ext):
  21.             # Rename the file with the prefix and suffix
  22.             new_name = prefix + filename.rsplit('.', 1)[0] + suffix + file_ext
  23.             os.rename(os.path.join(current_directory, filename), os.path.join(current_directory, new_name))
  24.             edited_files.append((filename, new_name))
  25.  
  26.     # Display the edited files
  27.     if edited_files:
  28.         print("\nEdited files:")
  29.         for old_name, new_name in edited_files:
  30.             print(f'{old_name} -> {new_name}')
  31.         print("\nFinished renaming files!")
  32.     else:
  33.         print("No files with the specified extension found.")
  34.    
  35.     # Wait for user input to close
  36.     input("\nPress Enter to exit...")
  37.  
  38. if __name__ == "__main__":
  39.     main()
  40.  
Advertisement
Add Comment
Please, Sign In to add comment