批量修改替换Markdown文件中字符

博客从Wordpress搬家到Hexo后各方面十分满意,但突然发现博客里面所有的图不见了。原来之前的图还都是原来的Wordpress链接

1
http://eliyar.biz/wp-contenthttps://eliyar.biz/images/2015/03/highlight.png

虽然我的博客图片不多,但是几十个图片一个个改还是比较麻烦的,遂写了个Python脚本如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/python
import os
dir ='/Users/Eliyar/Desktop/dir/'
dir2='/Users/Eliyar/Desktop/dir2/'
files=os.listdir(dir)
for f in files:
print f
file1=os.path.join(dir,f)
file_object=open(file1,'r')
all_the_txt=file_object.read()
file2=all_the_txt.replace('http://eliyar.biz/wp-content/images','/images')
file_object2=os.path.join(dir2,f)
file_object3=open(file_object2,'w')
file_object3.write(file2)
file_object.close()
file_object3.close()