Skip to content

Instantly share code, notes, and snippets.

@jeremejazz
Created May 5, 2018 06:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremejazz/6fbb105024530341364012b66251e085 to your computer and use it in GitHub Desktop.
Save jeremejazz/6fbb105024530341364012b66251e085 to your computer and use it in GitHub Desktop.
Files Organizer
#!/usr/bin/env python3
"""
This works for a specific set of files. (For modifications you can simply alter the regex pattern.)
This python script will organize files depending on the specified regex
For directories with files containing the following
Introduction-to-Jedi-Force-m1-01.mp4
midichlorian-Explained-m1-02.mp4
will move m1-01, m1-02 to beginning of the file resulting
m1-02_midichlorian-Explained.mp4
also files will be organized to directories based on module (m1, m2..) name
First copy script outside of folder.
To execute (requires python 3):
python3 renamer.py directory_name
"""
import os
import sys
import re
import shutil
if __name__ == "__main__":
directory = sys.argv[1]
print("Renaming files in folder " + directory)
target_dir = os.path.join(os.getcwd(), directory)
if (not os.path.exists(target_dir)):
raise Exception("Folder not found")
files = os.listdir(target_dir)
new_lst = []
for filename in files:
matches = re.search('(m\d+-\d+)\.mp4$', filename)
if matches:
start, total = matches.span()
crop = total - start + 1
basename = filename[:start - 1] + filename[-4:]
newname = matches.group(1) + "_" + basename
os.rename(os.path.join(target_dir, filename), os.path.join(target_dir,newname))
new_lst.append(newname)
# rename files
if len(new_lst) == 0:
new_lst = os.listdir(target_dir)
#copy to directory
files = os.listdir(target_dir)
for filename in sorted(new_lst):
module = filename.split("-")[0]
module_dir = os.path.join(target_dir, module)
if not os.path.exists(module_dir):
os.mkdir(module_dir)
shutil.move(os.path.join(target_dir, filename), os.path.join(module_dir, filename))
print ("Done organizing :)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment