Advertisement
Guest User

Python Script to Rename Files and Folders and updates the .cue files

a guest
Aug 12th, 2023
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | Source Code | 0 0
  1. import os
  2.  
  3.  
  4. def replace_string_in_filenames_and_folders(folder_path, target_string):
  5.     try:
  6.         # Traverse directories in a bottom-up manner
  7.         for root, dirs, files in os.walk(folder_path, topdown=False):
  8.             for filename in files:
  9.                 if target_string in filename:
  10.                     new_filename = filename.replace(target_string, "")
  11.                     src = os.path.join(root, filename)
  12.                     dst = os.path.join(root, new_filename)
  13.                     os.rename(src, dst)
  14.  
  15.                 if filename.endswith(".cue"):
  16.                     cue_file_path = os.path.join(root, filename)
  17.                     with open(cue_file_path, 'r') as cue_file:
  18.                         cue_file_content = cue_file.read()
  19.                    
  20.                     new_cue_file_content = cue_file_content.replace(target_string, "")
  21.                    
  22.                     with open(cue_file_path, 'w') as cue_file:
  23.                         cue_file.write(new_cue_file_content)
  24.  
  25.             for dirname in dirs:
  26.                 if target_string in dirname:
  27.                     new_dirname = dirname.replace(target_string, "")
  28.                     src = os.path.join(root, dirname)
  29.                     dst = os.path.join(root, new_dirname)
  30.                     os.rename(src, dst)
  31.  
  32.         print("String replacement in filenames, folders, and .cue files completed successfully.")
  33.     except OSError as e:
  34.         print(f"Error occurred: {e}")
  35.  
  36.  
  37. if __name__ == "__main__":
  38.     user_string = input("Enter the string you want to replace: ")
  39.     folder_directory = input("Enter the folder directory: ")
  40.  
  41.     replace_string_in_filenames_and_folders(folder_directory, user_string)
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement