diff --git a/FileOrganizer/FileOrganizer.py b/FileOrganizer/FileOrganizer.py index 834db468..0ca91093 100644 --- a/FileOrganizer/FileOrganizer.py +++ b/FileOrganizer/FileOrganizer.py @@ -4,23 +4,40 @@ # Prompt the user for the directory path to organize files path = input("Enter path: ") -# List all files in the specified directory -files = os.listdir(path) +# Check if the directory exists +if not os.path.exists(path): + print("Error: The specified directory does not exist.") +else: + # List all items in the specified directory + files = os.listdir(path) # Iterate through each file in the directory -for file in files: - # Split the filename and extension - filename, extension = os.path.splitext(file) - - # Remove the leading dot from the extension for folder naming - extension = extension[1:] - - # Check if a directory for the file extension already exists - if os.path.exists(path + '/' + extension): - # Move the file to the corresponding extension folder - shutil.move(path + '/' + file, path + '/' + extension + '/' + file) - else: - # If the directory does not exist, create it - os.makedirs(path + '/' + extension) - # Move the file to the newly created extension folder - shutil.move(path + '/' + file, path + '/' + extension + '/' + file) + for file in files: + file_path = os.path.join(path, file) + + # Skip directories + if os.path.isdir(file_path): + continue + + # Split the filename and extension + filename, extension = os.path.splitext(file) + extension = extension[1:] if extension else "NoExtension" # Handle files without extensions + + # Destination folder for the extension + dest_folder = os.path.join(path, extension) + + # Create the directory if it does not exist + if not os.path.exists(dest_folder): + os.makedirs(dest_folder) + + # Handle duplicate files by renaming them + dest_file_path = os.path.join(dest_folder, file) + counter = 1 + while os.path.exists(dest_file_path): + newfilename = f"{filename}{counter}.{extension}" if extension != "NoExtension" else f"{filename}_{counter}" + dest_file_path = os.path.join(dest_folder, new_filename) + counter += 1 + + # Move the file + shutil.move(file_path, dest_file_path) + print(f"Moved: {file} → {dest_file_path}") \ No newline at end of file