Skip to content

Instantly share code, notes, and snippets.

@sakydev
Last active September 3, 2021 09:28
Show Gist options
  • Save sakydev/7909812265e08a39532217883bfe2c6c to your computer and use it in GitHub Desktop.
Save sakydev/7909812265e08a39532217883bfe2c6c to your computer and use it in GitHub Desktop.
py: organize a directory by file type
# iterates over each file in source directory
# and moves to target directory under folders by file type
# I'm using this to automatically cleanup my Downloads folder on Windows 10
# which always looked like a mess before
from os import listdir, path, mkdir, rename
import shutil
inputDir = 'C:/Users/{user}/Downloads'
outputDir = 'G:/Downloads'
mapping = {
'video': ['mp4', 'mpeg', 'wmv', 'mov', 'flv'],
'audio': ['wav', 'mp3'],
'images': ['jpg', 'jpeg', 'png', 'ico'],
'torrents': ['torrent'],
'subtitles': ['srt'],
'zips': ['zip'],
'software': ['exe', 'msi'],
'files': ['html', 'php', 'css', 'js', 'py', 'csv', 'json', 'pdf', 'docx', 'txt'],
'sql': ['sql']
}
for file in listdir(inputDir):
fullFilePath = inputDir + '/' + file
extension = path.splitext(file)[1].replace('.', '')
for folder, extensions in mapping.items():
if extension in extensions:
destination = outputDir + '/' + folder
if not path.exists(destination):
mkdir(destination)
status = shutil.move(fullFilePath, destination)
if status:
print(f'Moved {fullFilePath} to {destination}')
else:
print(f'____ FAILED TO MOVE {fullFilePath} to {destination}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment