anon8071136

WallpaperRenamerPlus

Jul 31st, 2024 (edited)
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.59 KB | Source Code | 0 0
  1. import os
  2. import random
  3. import string
  4. import hashlib
  5. import time
  6.  
  7. # Directory containing the files
  8. directory = r'C:\Path\to\your\wallpapers'
  9.  
  10. """
  11. This script renames files in a specified directory to random 6-character alphanumeric filenames consisting
  12. of uppercase letters and digits. It includes the following features:
  13.  
  14. 1. Scans the directory and identifies all the files in it.
  15. 2. Calculates hashes for old files (files that already have 6-character names).
  16. 3. Calculates hashes for new files (files with filenames not exactly 6 characters long).
  17. 4. Compares hashes of old files and prompts the user to delete duplicates if conflicts are detected.
  18. 5. Deletes new files with hashes that match old files, ensuring no duplicate content.
  19. 6. Deletes new files with hashes that match other new files.
  20. 7. Renames remaining new files to unique 6-character alphanumeric filenames.
  21. 8. Prints detailed messages for each file, indicating actions taken (skipping, renaming, deleting).
  22. 9. Provides a summary at the end of the script, indicating how many files it scanned, skipped, renamed, deleted,
  23.   and the count of each file type.
  24. 10. Displays the total time the script took to run.
  25. """
  26.  
  27. # Function to generate a random filename
  28. def generate_random_filename(length=6):
  29.     characters = string.ascii_uppercase + string.digits
  30.     return ''.join(random.choice(characters) for _ in range(length))
  31.  
  32. # Function to calculate the Blake2b hash of a file
  33. def calculate_hash(file_path):
  34.     hasher = hashlib.blake2b()
  35.     try:
  36.         with open(file_path, 'rb') as f:
  37.             for chunk in iter(lambda: f.read(4096), b""):
  38.                 hasher.update(chunk)
  39.         return hasher.hexdigest()
  40.     except Exception as e:
  41.         print(f"Error calculating hash for {file_path}: {e}")
  42.         return None
  43.  
  44. # Function to rename files in the directory
  45. def rename_files(directory):
  46.     start_time = time.time()
  47.     scanned_count = 0
  48.     skipped_count = 0
  49.     renamed_count = 0
  50.     duplicate_count = 0
  51.     file_type_counts = {}
  52.     old_files_hashes = {}
  53.     new_files_hashes = {}
  54.     new_files = []
  55.  
  56.     # Step 1: Scan the directory and identify all the files in it
  57.     print("Scanning directory and identifying files...")
  58.     for filename in os.listdir(directory):
  59.         file_path = os.path.join(directory, filename)
  60.         if os.path.isfile(file_path):
  61.             scanned_count += 1
  62.             file_name, file_extension = os.path.splitext(filename)
  63.  
  64.             # Count file types
  65.             file_extension = file_extension.lower()
  66.             if file_extension not in file_type_counts:
  67.                 file_type_counts[file_extension] = 0
  68.             file_type_counts[file_extension] += 1
  69.  
  70.             # Categorize files as old or new
  71.             if len(file_name) == 6:
  72.                 # Step 2: Calculate hashes for old files
  73.                 file_hash = calculate_hash(file_path)
  74.                 if file_hash:
  75.                     if file_hash in old_files_hashes:
  76.                         old_files_hashes[file_hash].append(filename)
  77.                     else:
  78.                         old_files_hashes[file_hash] = [filename]
  79.                     skipped_count += 1
  80.                     print(f'Skipping "{filename}" (already 6 characters long) Hash: {file_hash}')
  81.             else:
  82.                 # Step 3: Calculate hashes for new files
  83.                 file_hash = calculate_hash(file_path)
  84.                 if file_hash:
  85.                     new_files.append((filename, file_path, file_hash))
  86.                     if file_hash in new_files_hashes:
  87.                         new_files_hashes[file_hash].append(filename)
  88.                     else:
  89.                         new_files_hashes[file_hash] = [filename]
  90.  
  91.     # Check for conflicts among old files
  92.     conflict_files = [(hash, files) for hash, files in old_files_hashes.items() if len(files) > 1]
  93.     if conflict_files:
  94.         print(f"\nDetected {len(conflict_files)} conflicts among old files:")
  95.         for hash, files in conflict_files:
  96.             print(f"Hash: {hash}")
  97.             for file in files:
  98.                 print(f" - {file}")
  99.        
  100.         user_input = input("Do you want to delete these duplicates? (y/n): ").strip().lower()
  101.         if user_input == 'y':
  102.             for hash, files in conflict_files:
  103.                 for file in files[1:]:  # Keep the first file, delete the rest
  104.                     os.remove(os.path.join(directory, file))
  105.                     duplicate_count += 1
  106.                     print(f'Deleting "{file}" (duplicate content found among old files)')
  107.  
  108.     # Step 4: Delete new files with hashes that match old files
  109.     print("Checking for duplicates and deleting if found...")
  110.     remaining_new_files = []
  111.     for filename, file_path, file_hash in new_files:
  112.         if file_hash in old_files_hashes:
  113.             duplicate_count += 1
  114.             os.remove(file_path)
  115.             print(f'Deleting "{filename}" (duplicate content found with existing 6-character filename)')
  116.         elif len(new_files_hashes[file_hash]) > 1:
  117.             duplicate_count += 1
  118.             new_files_hashes[file_hash].remove(filename)
  119.             os.remove(file_path)
  120.             print(f'Deleting "{filename}" (duplicate content found with another new file)')
  121.         else:
  122.             remaining_new_files.append((filename, file_path, file_hash))
  123.  
  124.     # Step 5: Rename remaining new files
  125.     print("Renaming remaining new files...")
  126.     for filename, file_path, file_hash in remaining_new_files:
  127.         file_name, file_extension = os.path.splitext(filename)
  128.  
  129.         # Generate a unique filename
  130.         new_filename = generate_random_filename() + file_extension
  131.         new_file_path = os.path.join(directory, new_filename)
  132.         while os.path.exists(new_file_path):
  133.             new_filename = generate_random_filename() + file_extension
  134.             new_file_path = os.path.join(directory, new_filename)
  135.        
  136.         os.rename(file_path, new_file_path)
  137.         renamed_count += 1
  138.         print(f'Renaming "{filename}" to "{new_filename}"')
  139.  
  140.     end_time = time.time()
  141.     total_time = end_time - start_time
  142.  
  143.     # Summary
  144.     print("\nSummary:")
  145.     print(f"Total files scanned: {scanned_count}")
  146.     print(f"Files skipped: {skipped_count}")
  147.     print(f"Files renamed: {renamed_count}")
  148.     print(f"Duplicates deleted: {duplicate_count}")
  149.     for file_type, count in file_type_counts.items():
  150.         print(f"{file_type.upper()} files scanned: {count}")
  151.     print(f"Total time taken: {total_time:.2f} seconds")
  152.  
  153.     # Pause at the end
  154.     input("Press Enter to exit...")
  155.  
  156. # Run the renaming process
  157. rename_files(directory)
  158.  
Advertisement
Add Comment
Please, Sign In to add comment