Tag Archives: python

Simple Python automation script to include content inside files

Bored of writing the same text chunk for your online store products description or ever wanted to have an “include” directive in JavaScript?

Here is a tiny automation script made in Python, i use it to include repetitive content inside HTML files, it read all *.html files (the extension can be changed on line 30) line by line in the directory the script is executed from and any {include=filename} tag found is replaced by the file “filename” content, it is fully recursive.

Note : The script do not check for circularity… so do not include a file including itself or similar stuff 🙂

Note : I am also using a variant written in the Anubis language for JavaScript which include a simple #include filename directive, that variant is also a tiny automatic build system which look for changes in a directory and build automatically the application package consisting of a single JS and CSS minified file if a file has changed, that way i just focus on writing code, the build system produce everything in the background when it detect a change and to test the app i just have to refresh the page in the browser, i may share it one day but the code is uglier than this. 🙂

# -*- coding: utf-8 -*-
#!/usr/bin/python

import os
import re
import sys
import glob

include_regex = re.compile("{include=(.*?)}")

def get_line_content(file):
    content = ""
    current_line = 0
    
    with open(file, 'r') as f:
        for line in f:
            inc = include_regex.search(line)
            if inc:
                inc_filename = inc.group(1)
                content += get_line_content(inc_filename)

                print("including " + inc_filename + ", include directive found in file " + file + " at line " + str(current_line))
            else:
                content += line
            current_line += 1
        f.close()
    return content

os.chdir(".")
for file in glob.glob("*.html"):
    head, tail = os.path.split(file)
    
    output_filename = "output/" + tail
    
    content = ""
    
    print("processing " + file)
    
    content = get_line_content(file)
    
    print("producing " + output_filename)
    
    f = open(output_filename, 'w')
    f.write(content)
    f.close()

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...