Advertisement
EmptySet5150

Sort ext to directory py3

Apr 7th, 2025
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | Software | 0 0
  1. import os
  2. import shutil
  3. import argparse
  4.  
  5.  
  6. def sort_files_by_extension(source_dir):
  7.     # Get the list of files in the source directory
  8.     files = [f for f in os.listdir(source_dir) if os.path.isfile(os.path.join(source_dir, f))]
  9.  
  10.     for file in files:
  11.         # Get the file extension
  12.         file_extension = file.split('.')[-1] if '.' in file else 'no_extension'
  13.  
  14.         # Create the directory for the extension if it doesn't exist
  15.         extension_dir = os.path.join(source_dir, file_extension)
  16.         if not os.path.exists(extension_dir):
  17.             os.makedirs(extension_dir)
  18.  
  19.         # Move the file to the appropriate directory
  20.         source_file = os.path.join(source_dir, file)
  21.         destination_file = os.path.join(extension_dir, file)
  22.  
  23.         # Move the file
  24.         shutil.move(source_file, destination_file)
  25.         print(f'Moved: {file} to {extension_dir}')
  26.  
  27.  
  28. if __name__ == "__main__":
  29.     # Set up argument parsing
  30.     parser = argparse.ArgumentParser(description="Sort files by extension into directories.")
  31.     parser.add_argument("source_directory", help="Path to the directory containing files to sort")
  32.  
  33.     # Parse the command-line arguments
  34.     args = parser.parse_args()
  35.  
  36.     # Call the function with the provided source directory
  37.     sort_files_by_extension(args.source_directory)
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement