1
\$\begingroup\$

I'm still new to programming and I'm not confident about this code. I recently created this File Organizer that organizes files in folders based on their extensions. How can I make this code cleaner?

# File Organizer - organizes file in folders based on their extensions.
# 03/05/2020

import shutil, os

root_path = "C:\\YourDesiredPath" 
os.chdir(root_path) 
dirfiles = os.listdir(root_path) 

class FileOrganizer():

    # store extensions and folder names
    mydir = {}

    def name_folder(self):
        for file in dirfiles: 
            ext = os.path.splitext(file)[1]
            if ext != '': # if file has an extension
                self.mydir[ext] = (ext + " FOLDER").upper()

    def create_folder(self):
        for folder in list(self.mydir.values()): 
            if not os.path.isdir(folder): 
                os.mkdir(os.path.join(root_path,folder))

    def organize_files(self):
        for file in dirfiles:
            # for files iterated, check if it matches the ext and move it to ext folder
            for ext in [*self.mydir]:
                if file.endswith(ext):
                    try:
                        shutil.move(file,self.mydir[ext])
                    except :
                        print(f"{file} already exists in {self.mydir[ext]}")


file_organizer = FileOrganizer() 
file_organizer.name_folder()
file_organizer.create_folder()
file_organizer.organize_files()
```
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You might want to take a look at this question from the same day. It seems to be similar to what you are doing, albeit not the same. The answers contain general tips that apply to your problem as well. \$\endgroup\$
    – Alex Povel
    May 4 '20 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.