S.M. Oliva

Sorting My Files with Python

S.M. Oliva

December 23, 2019

I ghostwrite blogs for multiple clients. In my normal workflow, I have a “drafts” directory for each week. Within the weekly directory, I then label individual drafts using the format YYYY-MM-DD-clientname_post-title.md.

In past years, I would end my workweek by sorting the draft files into individual client archive folders. But I neglected to do that for this entire year. So now as the new year approaches, I found myself with nearly 1,100 unsorted files.

Rather then sit down and manually sort each folder, I decided to try and create a Python program to do the job automatically. After a couple of hours of reading through Python's documentation, I actually came up with something that worked.

Here is a slightly modified version of my program:**

import glob, os, shutil

clients = [	'adams', 'baker',
            'clark', 'daniels']	

for client in clients:
    dest = '/home/smoliva/Sync/Blogging/Archive/' + client.title()

    if not os.path.exists(dest):
        os.mkdir(dest)
    
    posts = glob.glob('/home/smoliva/Sync/drafts/*/*-' + client + '*')
    posts.sort()

    for post in posts:
        print("Moving: " + post + " to " + dest)  
        shutil.move(post, dest)

One thing I noticed when running the program was that it apparently overwrote the content of sub-directories that already existed in my Archive directory. This ended up deleting the existing files in that folder. Fortunately, I made backups of both my drafts and Archive folders before I ran the program. So I simply merged the contents of the backup folders into the new folders. Of course, before I use this program again, I will need to look into what happened here.

** The client names in this code are obviously not my actual clients. Some of the paths are also altered to eliminate any client identifying information.