问题描述
我有一些markdown笔记是按日期排列的,以日期为标题。因为我以前用的是typora,在typora中打开文件时显示的是页面顶端,所以我写markdown的时候,会把新的日期放在最前面,
# 2022-01-17
...
# 2022-01-16
...
# 2022-01-15
...
最近我用marktext,发现marktext中打开文件时会自动跳到页面最低下,所以我需要将上述的文件按照一级标题倒序输出:
# 2022-01-15
...
# 2022-01-16
...
# 2022-01-17
...
实现方式
import os
file1 = "./WeeklyPlans.md"
file2 = "./WeeklyPlans.md"
lines = []
block = []
lino = 0
with open(file1, "r") as f:
line = f.readline()
while line:
if line.strip().startswith("# "): #检查是否以# 开始
if lino > 0:
lines.append(block)
lino += 1
block = []
block.append(line)
else:
block.append(line)
lino += 1
print(lino)
line = f.readline()
lines.append(block)
with open(file2, "w") as f:
for block in reversed(lines): # 倒序输出
f.writelines(block)