Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved script and added functionality #404

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 35 additions & 18 deletions FileOrganizer/FileOrganizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")