Skip to content

Instantly share code, notes, and snippets.

@aslamanver
Created November 1, 2020 19:46
Show Gist options
  • Save aslamanver/2b07996fb58b6825685dc896d275598e to your computer and use it in GitHub Desktop.
Save aslamanver/2b07996fb58b6825685dc896d275598e to your computer and use it in GitHub Desktop.
Files categorize by year and month - This script will categorize all the files in a directory to a folders.
#!/bin/bash
# This script will move all the files in a directory to a folders
# with the name of year and month which it gets from the file's created time.
# Run: python categorizer.py /home/aslam/screenshots
# It will categorize all of your files by folders as the name of year and month
# Ex: 1.jpg will be moved to 2020-10_1 folder as 1.jpg created at 2020-10-15 also
# the last number after underscore is the count of the directory
import os
import sys
import time
from datetime import datetime
directory = sys.argv[1]
for name in os.listdir(directory):
file = os.path.join(directory, name)
if not os.path.isdir(file):
created = os.path.getmtime(file)
txtdate = datetime.fromtimestamp(created).strftime("%Y-%m")
datedirectory = os.path.join(directory, txtdate)
if not os.path.exists(datedirectory):
os.makedirs(datedirectory)
os.rename(file, os.path.join(datedirectory, name))
print('%s moved to %s' % (name, datedirectory))
for name in os.listdir(directory):
cdirectory = os.path.join(directory, name)
if os.path.isdir(cdirectory) and '_' not in name:
count = len(os.listdir(cdirectory))
newname = cdirectory + '_' + str(count)
os.rename(cdirectory, newname)
print('%s renamed as %s' % (cdirectory, newname))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment