修改博文中的图片格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#_python3@linux _#
#_date:2023-12-17_#
#_转换博文中插入图片的格式webp to webp,修改插入语句和图片_#
#_encoding = utf-8_#

import os
import re
from PIL import Image


def change_to_webp():
"""
将 source\_posts目录下的所有图片格式(webp/webp)转换成webp。
并将对应的md文件中插入图片的语句相应的更改成webp.如:<img src="./1.webp" /> ==>>> <img src="./1.webp" />
"""
fold = r"/run/media/xiaoyx/Data/BLOG/yxhsiao/source/_posts"
imgs = [
os.path.join(p, j) for p, d, f in os.walk(fold) for j in f
if re.search('\.webp$|\.webp$', j)
]
for img in imgs:
im = Image.open(img).convert('RGB')
im.save(re.sub('webp|webp', 'webp', img))
os.remove(img)

files = [
os.path.join(fold, i) for i in os.listdir(fold)
if re.search('\.md$', i)
]
for file in files:
with open(file, 'r',
encoding='utf-8') as f, open(f'{file}.bak',
'w',
encoding='utf-8') as newfile:
for line in f.readlines():
newfile.write(re.sub('webp|webp', 'webp', line))
os.remove(file)
os.rename(f'{file}.bak', file)


if __name__ == "__main__":
change_to_webp()