之前写文章,一直没有写时间,也没多大问题。后来换了一台电脑后,上传新文章全部乱了顺序。
原来之前是按文件的创建时间排序,而我这复制过来的文件,创建时间几乎一样。所以博客乱了套。后来发现文件的修改时间还是以前的,于是给每篇文章,按修改时间添加了date。
代码如下
import os
import sys
import time
path = r'E:\WeiLai\OneDrive\blog\source\_posts'
for root, dir, files in os.walk(path):
for file in files:
full_path = os.path.join(root, file)
if '.md' in full_path:
mtime = os.stat(full_path).st_mtime
file_modify_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(mtime))
date = 'date: '+file_modify_time
with open (full_path,'r', encoding='UTF-8') as f:
s = f.read()
q = s.partition('tags:')
t = q[0] + date +'\n' + q [1] + q[2]
with open (full_path,'w', encoding='UTF-8') as f:
f.write(t)