Moving Files By Name

…where the name is made up of the date and time.

I’ve got a lot of image files that I tend to dump into whatever directory I feel like.
This simple python script will create directories and move files around based on the file name, as long as the filename follows the following format YYYYMM. Bascially as long as the first 6 characters are integers it should work. In my file system that’s fine In yours the same may not be true. If the first 6 characters is not an integer then it will leave them alone.

Notice I’m not checking for JPG/MP4 files only; I’m not checking that the year or month are valid values; I’m not checking the EXIF values and basing it on them if the filename is not valid; there are lots of really cool things I could do as well but I don’t need those because that’s how my files are set out. I’m not building in lots of features that don’t touch my use-case.

import os
import shutil

path = '/home/mike/TestPython/'
os.chdir(path)

for file in os.walk(path):
    for name in file[2]:
        year = name[:4]
        month = name[4:6]
        if name[:6].isdigit():
            if not os.path.exists(year):
                os.makedirs(year)
            if not os.path.exists(year + "/" + month):
                os.makedirs(year + "/" + month)
            src = file[0] + "/" + name
            dst = path + year + "/" + month + "/"+name
            shutil.move(src, dst)

Once you’ve moved all the files into their new homes delete all the empty directories. This code has been ever so slightly modifed from this StakOverflow post. It was modified for Python 3, by adding brackets to the print syntax:

import os
currentDir = '/home/mike/TestPython/'

index = 0
for root, dirs, files in os.walk(currentDir):
    for dir in dirs:
        newDir = os.path.join(root, dir)
        index += 1
        print (str(index) + " ---> " + newDir)
        try:
            os.removedirs(newDir)
            print("Directory empty! Deleting...")
            print(" ")
        except:
            print("Directory not empty and will not be removed")
            print(" ")

Simple Java Insertion Sort

package insertionshort;
public class InsertionShort {
    public static void main(String[] args) {
        int[] a = {123, 235, 23, 46, 34, 2, 45, 235, 25, 65, 46, 2345, 25, 246, 24, 5246, 24, 6};
        intInsertionSort(a);
    }
    public static void intInsertionSort(int[] a) 
    {
        for (int i = 0; i < a.length; i++) {
            int temp = a[i];
            int j;
            for (j = i - 1; j >= 0 && temp < a[j]; j--) 
            {
                a[j + 1] = a[j];
            }
            a[j + 1] = temp;
            for (int f = 0; f < a.length; f++) 
            {
                System.out.print(a[f] + "\t");
            }
            System.out.println();
        }
    }
}