In [1]:
import os

def save_template(directory, tag):
    tag_template = """---
layout: blog
tag_search: %s
---

{%% include tags_index.html %%}""" %(tag)
    
    total_path = os.path.join(directory, tag) + '/index.html'
    f = open(total_path, 'a')
    f.write(tag_template)
    f.close()

directory = 'tags'
    
dir_post = '_posts'
file_list = []

start_tags_line = 'tags:'
tag_set = set()
tag_list = []

# All file names where I'm looking the tags
for file in os.listdir(dir_post):
    if file.endswith(".md") or file.endswith(".markdown"):
        file_list.append(os.path.join(dir_post, file))

# All tags into list
for file in file_list:
    with open(file, "r") as post:
        for line in post.readlines():
            if line.startswith(start_tags_line):
                text, tags = line.split(start_tags_line)
                
                tags = ''.join(tags.split())
                if tags.endswith('/n'):
                    tags, args = tags.split('/n')

                a = [s.strip() for s in tags[1:-1].split(',')]
                tag_list.append(a)

# In tag_list are tag repeated. Using set, are remove.
for i in range(len(tag_list)):
    a = set(tag_list[i])
    tag_set= tag_set | a
    
tag_list = list(tag_set)
for i in range(len(tag_list)):
    tag_list[i] = tag_list[i].lower()

if not os.path.exists(directory):
    os.makedirs(directory)
    
print(tag_list)
    
for tag in tag_list:
    total_path = os.path.join(directory, tag)
    print(total_path)
    if not os.path.exists(total_path):
        os.makedirs(total_path)
        print(directory, tag, '\n\n\n')
        save_template(directory, tag)


['test', 'jekyll', 'example', 'tag2', 'tag3', 'tag1']
tags/test
tags test 



tags/jekyll
tags jekyll 



tags/example
tags example 



tags/tag2
tags tag2 



tags/tag3
tags tag3 



tags/tag1
tags tag1 




In [12]:
f = open('tag1/test.html', 'a')
f.write('spam')
f.close()

In [4]:
path = os.path.join('tag1', 'tag')
path


Out[4]:
'tag1/tag'

In [ ]: