之前寫文章,一直沒有寫時間择卦,也沒多大問題睁壁。后來換了一臺電腦后背苦,上傳新文章全部亂了順序。
原來之前是按文件的創(chuàng)建時間排序潘明,而我這復(fù)制過來的文件行剂,創(chuàng)建時間幾乎一樣。所以博客亂了套钳降。后來發(fā)現(xiàn)文件的修改時間還是以前的厚宰,于是給每篇文章,按修改時間添加了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)