Requirements describe

We now have a folder with hundreds of Markdown files, and we want to add the date and title attributes to the second and third lines of each file, respectively.

How does Python read markdown files

We only need to use the open function, but the decoding format must be UTF-8, otherwise an error will be reported

How do I get the creation time of a file

t = os.path.getmtime(filePath + '\ \' + i)
Copy the code

How to get the contents of a specified line of a file (via the linecache package)

import linecache
categories_add = 'categories: ' + linecache.getline(filePath + '\ \' + i, 5).strip()[2:]
Copy the code

All the code

import os
import time
import linecache
filePath = 'G:\HEXO\ Add file name and time \\test'
def TimeStampToTime(timestamp) :
    timeStruct = time.localtime(timestamp)
    return time.strftime('%Y-%m-%d',timeStruct)
for i in os.listdir(filePath):
    print(i)
    t = os.path.getmtime(filePath + '\ \' + i)
    print(TimeStampToTime(t))
    file = open(filePath + '\ \' + i, "r",encoding='utf-8') 

    text = file.read()
    # print(text)
    content_add = i[:-3]
    text_add = TimeStampToTime(t)
    pointer = text.find("date:")
    pos = text.find("title:")
    
    categories_add = 'categories: ' + linecache.getline(filePath + '\ \' + i, 5).strip()[2:]
    print(categories_add)
    
    ifpointer ! = -1& pos ! = -1:
            # text = text[:pointer+6] + text_add + text[pointer+6:]
            # text = text[:pos+7] + content_add + text[pos+7:]
            tagP = text.find("tags:")
            text = text[:tagP] + categories_add  + '\n' + text[tagP:]

            file = open(filePath + '\ \' + i, "w",encoding='utf-8')
            file.write(text)
            file.close()
    # Below is the write title

    # print(i[:-3])
    # file = open(filePath + '\\' + i, "r",encoding='utf-8')

    # content = file.read()
    # content_add = i[:-3]
    # pos = content.find("title:")
    # if pos != -1:
    # content = content[:pos+6] + content_add + content[pos+6:]
    # file = open(filePath + '\\' + i, "w")
    # file.write(content)
    # file.close()
Copy the code