Last active
December 26, 2019 13:00
-
-
Save isaacimholt/610018e09388ab011805f0a98587a0b2 to your computer and use it in GitHub Desktop.
sort files for byunw on /r/learnpython
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import shutil | |
# We define this mapping first to make adding new types easy. | |
# I've taken the liberty of adding support for some extra types. | |
folder_to_extensions = { | |
'PDF': {'pdf'}, | |
'Documents': {'doc', 'docx'}, | |
'Text': {'txt', 'rtf'}, | |
'EXE': {'exe', 'msi'}, | |
'ZIP': {'zip', '7z', 'rar'}, | |
'Images': {'jpg', 'jpeg', 'png', 'gif'}, | |
} | |
# We rearrange the previous map for performance. In this way we can | |
# quickly obtain the target folder from a file extension in O(1) time. | |
# For simplicity we could have simply defined this map by hand, but the | |
# previous dictionary we defined is easier to alter by hand if we want | |
# to rename folders or add extensions. | |
extension_to_folder = {e: f for f, s in folder_to_extensions.items() for e in s} | |
source_folder = 'C:/Users/byunw/Downloads' | |
target_folder = 'C:/Users/byunw/Downloads' | |
for filename in os.listdir(source_folder): | |
# skip files with no extension | |
if '.' not in filename: | |
continue | |
# we know there is at least 1 '.' in the file, so let's split the string on that file extension | |
file_extension = filename.rsplit('.', maxsplit=1)[1].lower() | |
extension_folder = extension_to_folder.get(file_extension) | |
if extension_folder is None: | |
print(f'Unsupported file extension: "{file_extension}"!') | |
continue | |
shutil.move(f'{source_folder}/{filename}', f'{target_folder}/{extension_folder}') | |
print("Every supported file in the Downloads folder is now sorted into corresponding folders") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment