![]() |
File sorting by user-chosen category - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: File sorting by user-chosen category (/thread-34750.html) |
File sorting by user-chosen category - Bachelar - Aug-28-2021 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) |