Skip to content

Commit 9cd8c7c

Browse files
improved script (DhanushNehru#404)
1 parent 2a419b1 commit 9cd8c7c

File tree

1 file changed

+35
-18
lines changed

1 file changed

+35
-18
lines changed

FileOrganizer/FileOrganizer.py

Lines changed: 35 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,40 @@
44
# Prompt the user for the directory path to organize files
55
path = input("Enter path: ")
66

7-
# List all files in the specified directory
8-
files = os.listdir(path)
7+
# Check if the directory exists
8+
if not os.path.exists(path):
9+
print("Error: The specified directory does not exist.")
10+
else:
11+
# List all items in the specified directory
12+
files = os.listdir(path)
913

1014
# Iterate through each file in the directory
11-
for file in files:
12-
# Split the filename and extension
13-
filename, extension = os.path.splitext(file)
14-
15-
# Remove the leading dot from the extension for folder naming
16-
extension = extension[1:]
17-
18-
# Check if a directory for the file extension already exists
19-
if os.path.exists(path + '/' + extension):
20-
# Move the file to the corresponding extension folder
21-
shutil.move(path + '/' + file, path + '/' + extension + '/' + file)
22-
else:
23-
# If the directory does not exist, create it
24-
os.makedirs(path + '/' + extension)
25-
# Move the file to the newly created extension folder
26-
shutil.move(path + '/' + file, path + '/' + extension + '/' + file)
15+
for file in files:
16+
file_path = os.path.join(path, file)
17+
18+
# Skip directories
19+
if os.path.isdir(file_path):
20+
continue
21+
22+
# Split the filename and extension
23+
filename, extension = os.path.splitext(file)
24+
extension = extension[1:] if extension else "NoExtension" # Handle files without extensions
25+
26+
# Destination folder for the extension
27+
dest_folder = os.path.join(path, extension)
28+
29+
# Create the directory if it does not exist
30+
if not os.path.exists(dest_folder):
31+
os.makedirs(dest_folder)
32+
33+
# Handle duplicate files by renaming them
34+
dest_file_path = os.path.join(dest_folder, file)
35+
counter = 1
36+
while os.path.exists(dest_file_path):
37+
newfilename = f"{filename}{counter}.{extension}" if extension != "NoExtension" else f"{filename}_{counter}"
38+
dest_file_path = os.path.join(dest_folder, new_filename)
39+
counter += 1
40+
41+
# Move the file
42+
shutil.move(file_path, dest_file_path)
43+
print(f"Moved: {file}{dest_file_path}")

0 commit comments

Comments
 (0)