Skip to content

Instantly share code, notes, and snippets.

@affo
Created March 20, 2014 14:40
Show Gist options
  • Save affo/9665249 to your computer and use it in GitHub Desktop.
Save affo/9665249 to your computer and use it in GitHub Desktop.
Script to order files by extension in a directory. Once run, directories named with files extensions will be created. Can be run periodically.
#!/usr/bin/python
import os
import logging
logging.basicConfig(filename='clean.log', filemode='w', level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(message)s')
wd = os.getcwd()
alll = os.listdir(wd)
files = []
dirs = []
for dirr in alll:
path = os.path.join(wd, dirr)
if os.path.isdir(path):
dirs.append(dirr)
for file in alll:
path = os.path.join(wd, file)
if file not in dirs:
files.append(file)
# REMOVE THE FILES YOU DON'T WANT TO BE TOUCHED.
# FIRST OF ALL, REMOVE THE SCRIPT ITSELF.
#files.remove('clean')
#files.remove('deldirs')
#files.remove('clean.log')
for file in files:
path = os.path.join(wd, file)
name, ext = file.split('.')
if ext:
w_dir = os.path.join(wd, ext)
if ext not in dirs:
os.mkdir(w_dir)
dirs.append(ext)
w_files = os.listdir(w_dir)
suffix = ''
i = 0;
while file in w_files:
i += 1
suffix = '__' + `i`
file = name + suffix + "." + ext
dest = os.path.join(wd, ext, file)
os.rename(path, dest)
logging.info(path + " moved to " + dest)
logging.info("DONE")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment