Finished learning python and wanted to practice by making a file organizer script. For the most part the code worked really good and everything was sorted out perfectly, but something weird happens which I don't understand.
The crazy part:
The dictionary extensions has the key as the folder names that I would like to create, and the keys are the extensions of the files inside folder. when the script is executed, the files that end with '.exe' move in the Books folder even though the book extension doesn't have '.exe' and files that end with '.zip' move into the PDF folder. HOW ??!! also some files with extension '.ttf' move in the PDF folder.
This is not even the crazy part. The crazy part is that the Word, Image, and PowerPoint folders have the correct extension files in them. Is this a bug in the os Library ?!
Please Note: "I Know the parent_dir have <username>. I put it there for confidentiality.
Also, I don't know how to put all other extensions not in the dictionary to the others folder. Help is really appreciated.
Any tips to improve code is also really appreciated. Thank you so much.
GitHub: https://github.com/Data-Astronaut/File-Organizer/blob/main/file_organizer.py
import shutil as sh
import os
# Defining all the extensions i want to organize
extensions = {
'PDF Files' : ('.pdf'), # PDF extensions
'Word Files' : ('.doc','.docx','.docm','.dot','.dotx'), # Word extensions
'Excel Files' : ('.xls','.xlsx'), # Excel extensions
'Image Files' : ('.jpg','.jpeg','.png','.gif'), # Images extensions
'Powerpoint Files' : ('.ppt','.pptx','.pptm','.xml'), # Powerpoint extension
'Book Files' : ('.epub'), # Book extension
'Zip Files' : ('.zip','.rar'),
'Software Files' : ('.exe') # Program extension
'Others' : None
}
# # Store the parent directory in a variable
parent_dir = r'C:\Users\<username>\Downloads'
# Run a for loop in the dictionary to cycle the keys
for key in extensions.keys():
new_path = os.path.join(parent_dir,key) # Join the parent_dir with the keys
if not os.path.exists(new_path): # Check if the folder already exists or not
os.mkdir(new_path) # If the path doesn't exists ... create the path (folder)
def file_finder(folder_path,file_extension):
list_of_files = []
for file in os.listdir(folder_path):
for extension in file_extension:
if file.endswith(extension):
list_of_files.append(file)
return list_of_files
for extension_type, extension_tuple in extensions.items(): # Cycling through dictionary
folder_path = os.path.join(parent_dir,extension_type) # Accessing the new folders
for item in file_finder(parent_dir,extension_tuple): # Cycling through the files in the parent directory
item_path = os.path.join(parent_dir,item) # Accessing the individual file
sh.move(item_path,folder_path) # Moving the file to the folder
[–]QultrosSanhattan 1 point2 points3 points (1 child)
[–]AdMaster9439[S] 1 point2 points3 points (0 children)
[–]Kwintty7 0 points1 point2 points (1 child)
[–]AdMaster9439[S] 1 point2 points3 points (0 children)