Python Forum

Full Version: File sorting by user-chosen category
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, y'all!
What I want to do is to sort epub files into category-based folders, I've got multiple categories and figured out a separator I'll put into every filename (cumbersome, yes, but I'll deal with that later). I've managed to figure out how to do it the crude way (see attached code). I know it could be done waaay better, because it's sloppy (and not very pythony). Furthermore, I'd love the script to auto-search the „category” (a tag) within the filename and create folder by itself.
Any help will be appreciated.
Thanks in advance!
        
        homedir = os.path.expanduser("~")
        path = os.path.join(homedir, 'OneDrive/PC/downloads')
        dst = os.path.join(homedir, 'OneDrive/Philosophy')
        files = os.listdir(path)
        increment = 0
        for file in files:
            name, ext = os.path.splitext(file)
            if fnmatch.fnmatchcase(file, '*; Philosophy.*'):
                if os.path.exists(dst) is True:
                    while os.path.exists(dst+'/'+f'{name}{ext}'):
                        if isinstance(increment, str):
                            increment = -1
                        increment += 1
                        try:
                            os.rename(dst+'/'+file, dst+'/'+f'{name}_{increment}{ext}')
                            return False
                        except Exception:
                            return True
                else:
                    os.makedirs(dst)
                shutil.move(os.path.join(path, file), dst)