|
| 1 | +import shutil |
| 2 | +import json |
| 3 | +import sys |
| 4 | +import os |
| 5 | +from tkinter import Tk |
| 6 | +from tkinter import filedialog |
| 7 | + |
| 8 | + |
| 9 | +def get_data(): |
| 10 | + with open(os.path.join(base_path, 'data/last_path.txt'), 'r') as fp: |
| 11 | + last_path = fp.read() |
| 12 | + |
| 13 | + with open(os.path.join(base_path, 'data/formats.json'), 'r') as fp: |
| 14 | + extensions = json.load(fp) |
| 15 | + |
| 16 | + with open(os.path.join(base_path, 'data/exclude.txt'), 'r') as fp: |
| 17 | + exclude = fp.read().strip().splitlines() |
| 18 | + |
| 19 | + return last_path, extensions, exclude |
| 20 | + |
| 21 | + |
| 22 | +def get_path(last_path): |
| 23 | + Tk().withdraw() |
| 24 | + path = filedialog.askdirectory(initialdir=last_path) |
| 25 | + return path |
| 26 | + |
| 27 | + |
| 28 | +def save_path(path): |
| 29 | + with open(os.path.join(base_path, 'data/last_path.txt'), 'w') as fp: |
| 30 | + fp.write(path) |
| 31 | + |
| 32 | + |
| 33 | +def move_file(file, new_path): |
| 34 | + try: |
| 35 | + dst = f'{new_path}/{file.name}' |
| 36 | + shutil.move(file.path, dst) |
| 37 | + print(f'Moved {file.name} to {new_path}') |
| 38 | + except Exception as e: |
| 39 | + print('[ERROR]', e) |
| 40 | + |
| 41 | + |
| 42 | +def check_folder(new_path): |
| 43 | + if not os.path.isdir(new_path): |
| 44 | + os.mkdir(new_path) |
| 45 | + |
| 46 | + |
| 47 | +def check_extension(file): |
| 48 | + _, file_ext = os.path.splitext(file.name) |
| 49 | + for type_, ext in extensions.items(): |
| 50 | + if file_ext.lower().strip('.') in ext: |
| 51 | + return type_ |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == '__main__': |
| 55 | + base_path = os.path.abspath('.') |
| 56 | + if getattr(sys, 'frozen', False): |
| 57 | + base_path = sys._MEIPASS # type: ignore |
| 58 | + |
| 59 | + last_path, extensions, exclude = get_data() |
| 60 | + |
| 61 | + path = get_path(last_path) |
| 62 | + if path != tuple(): |
| 63 | + for file in os.scandir(path): |
| 64 | + if file.is_file() and file.name not in exclude: |
| 65 | + type_ = check_extension(file) |
| 66 | + if type_: |
| 67 | + new_path = f'{path}/{type_}' |
| 68 | + check_folder(new_path) |
| 69 | + move_file(file, new_path) |
| 70 | + |
| 71 | + save_path(path) |
0 commit comments