Guest User

RestoreBackup

a guest
Apr 15th, 2024
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. import os
  2. import shutil
  3.  
  4. def process_directory(directory):
  5.     """
  6.    Process the specified directory.
  7.    - Delete layer 1 files.
  8.    - If any layer 2 folder is named "backup", move its files to layer 1 and delete the remaining layer 2 directories.
  9.    """
  10.     for root, dirs, files in os.walk(directory):
  11.         # Process layer 1 files
  12.         if root != directory:
  13.             for filename in files:
  14.                 file_path = os.path.join(root, filename)
  15.                 os.remove(file_path)
  16.  
  17.         # Process layer 2 folders
  18.         for subdir in dirs:
  19.             subdir_path = os.path.join(root, subdir)
  20.             if os.path.isdir(subdir_path):
  21.                 # Check if the folder is named "backup"
  22.                 if subdir.lower() == "backup":
  23.                     # Move files from layer 2 to layer 1
  24.                     for subfile in os.listdir(subdir_path):
  25.                         subfile_path = os.path.join(subdir_path, subfile)
  26.                         if os.path.isfile(subfile_path):
  27.                             shutil.move(subfile_path, os.path.join(root, subfile))
  28.                     # Delete the remaining layer 2 directory
  29.                     shutil.rmtree(subdir_path)
  30.                 else:
  31.                     # Check if the folder contains layer 2 files
  32.                     layer2_files = [f for f in os.listdir(subdir_path) if os.path.isfile(os.path.join(subdir_path, f))]
  33.                     if layer2_files:
  34.                         # Do not delete the layer 2 directory
  35.                         pass
  36.  
  37. # Detect the current directory
  38. current_directory = os.path.dirname(os.path.abspath(__file__))
  39.  
  40. # Process the current directory
  41. process_directory(current_directory)
  42.  
Add Comment
Please, Sign In to add comment