Blog Tags

Category: learning

I took a little bit of time this afternoon to write a short Python script to help with the tags on the blog site.

One problem with the Jekyll setup is that the tag pages must be built manually. At least, if you’re using GitHub it seems to be that way. I think there are some plug-ins that will do that for you automatically, but they aren’t part of what you’re allowed to do.

My script just works its way through my post folder and grabs the tag information from the front matter, combines it all together (avoiding duplication), and then spits out the markdown files that are needed to create the tag pages. It’s nothing fancy, and it’s short enough and simple enough to be posted here and be a reasonable length. I’ve removed the exact path names because I feel weird posting those.

import os

# Get all the files
os.chdir(post_directory)
filelist = os.listdir()

# Define variables
taglist = []

for filename in filelist:
    # Open the file
    readfile = open(filename, 'r')

    print('Reading file', filename)

    # Look for line with tags
    line = 'temp'

    while len(line) > 0:
        line = readfile.readline()
        if line[0:5] == 'tags:':
            break

    readfile.close()

    # Get the tags and add them to the list
    if len(line) > 0:
        tags = line[6:].split()
        print('Tags: ', tags)
        for tag in tags:
            if tag not in taglist:
                taglist.append(tag)
    else:
        print('Error in file', filename)

# Create tag files
os.chdir(tag_directory)

for tag in taglist:
    filename = tag + '.md'
    writefile = open(filename, 'w')
    writefile.write('---\n')
    writefile.write('layout: tagpage\n')
    writefile.write('title: "Tag: ' + tag + '"\n')
    writefile.write('tag: ' + tag + '\n')
    writefile.write('---\n')
    writefile.close()
Written on September 2, 2020