Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import shutil
- import argparse
- def sort_files_by_extension(source_dir):
- # Get the list of files in the source directory
- files = [f for f in os.listdir(source_dir) if os.path.isfile(os.path.join(source_dir, f))]
- for file in files:
- # Get the file extension
- file_extension = file.split('.')[-1] if '.' in file else 'no_extension'
- # Create the directory for the extension if it doesn't exist
- extension_dir = os.path.join(source_dir, file_extension)
- if not os.path.exists(extension_dir):
- os.makedirs(extension_dir)
- # Move the file to the appropriate directory
- source_file = os.path.join(source_dir, file)
- destination_file = os.path.join(extension_dir, file)
- # Move the file
- shutil.move(source_file, destination_file)
- print(f'Moved: {file} to {extension_dir}')
- if __name__ == "__main__":
- # Set up argument parsing
- parser = argparse.ArgumentParser(description="Sort files by extension into directories.")
- parser.add_argument("source_directory", help="Path to the directory containing files to sort")
- # Parse the command-line arguments
- args = parser.parse_args()
- # Call the function with the provided source directory
- sort_files_by_extension(args.source_directory)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement