之前寫文章,一直沒有寫時間,也沒多大問題。后來換了一臺電腦后,上傳新文章全部亂了順序。
原來之前是按文件的創建時間排序,而我這復制過來的文件,創建時間幾乎一樣。所以博客亂了套。后來發現文件的修改時間還是以前的,于是給每篇文章,按修改時間添加了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)
修改前
修改后