Python Scripting for Increased Workflow

1 min read

Scripting for Efficiency for Graphic Assets

After I finished up my first asset for the Gitcoin Asset Generator, it was time to export the various files that the web app needs to operate. This web app is built using Python and Django. Every hair .svg asset needs to be named with the following pattern <hairname>-<hexadecimal color>.svg and a text file needed to be made for the Django template. ex) DamosHair-#ED20207.svg. There are 9 hair colors. That means opening changing the color 9 times and renaming the file 9 times PER ASSET, plus a Django .txt version.

You already know, I wasn’t about to design more assets and have to manually rename and recolor a bunch of files. Uhhhno. I got to work and with the guidance of a friend experienced in Python we knocked out this script before lunch. Now, with one command, I could rename, recolor, and template n+ svg files rather than spend minutes per each file.


Here’s a video of it in action


The script itself

The SVG Exporter on Github

import os
import fileinput

#authored by Damien Gilliams and Guled Abdilahi on 10/15/2018

print ("\n\n~~~Start of Program~~~\n")

originalColor = "ed2027" //red hair :)
newColors = ["000000", "4E3521", "8C3B28", "B28E28", "F4EA6E", "F0E6FF", "4D22D2", "8E2ABE", "3596EC", "0ECF7C", "ED2027"]

# for the files in the dir
for root, dirs, files in os.walk("."):
    for filename in files:

        # if file ext ends in .svg
        if (os.path.splitext(filename)[1] == ".svg"):
            svgFile = open(filename, 'r')
            svgData = svgFile.read()
            svgFile.close()

            # make sure color exists in file
            if svgData.find(originalColor) == -1:
                print ("ERROR: Change fill color of " + filename + " to #ED2027 for script to work")
                continue

            newDirectory = os.path.splitext(filename)[0] + "_assets"
            os.makedirs(newDirectory, exist_ok=True)

            for newColor in newColors:

                newSvgFileData = svgData.replace(originalColor, newColor)

                newFileName = os.path.splitext(filename)[0] + "-" + newColor
                newFile = open(newDirectory + "/" + newFileName + ".svg", 'w')
                newFile.write(newSvgFileData)
                newFile.close

                print (newFileName + " was generated")

        # output replaced results to new file

print ("\n\n~~~Done!~~~\n")