Python Learning #09 - Simple Application

learn to use, learn for use

2020-01-06 Mike Lyou

After learning the file operations and directory operations, I eventually could use python to do some tasks.

This article may be updated for a long time, recording useful applications.

Catalog:

Replace single string in multiple markdown files

The first thing I wanna do is replacing all Chinese tags in my posts to English ones. In particular, I wanna replace all 学习笔记 with Notes in 10 posts.

The code is posted below.

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
# Ref: https://blog.csdn.net/shenxian1021/article/details/81873845
import os
import io
import fnmatch


def alter(file,old_str,new_str):  # replace string in a file
    file_data = ""
    with io.open(file, "r", encoding="utf-8") as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str,new_str)
            file_data += line
    with io.open(file,"w",encoding="utf-8") as f:
        f.write(file_data)

def main():
    basepath = "E:/GitHub/mikelyou.github.io/_posts"  # Attention: '/', not '\'
    with os.scandir(basepath) as entries:
        for entry in entries:
            if fnmatch.fnmatch(entry,'*.md'):         # select all *.md files
                    alter(entry,"学习笔记","Notes")   # the string to replace

if __name__ == '__main__':
    main()

Here is the results. I successfully replace all 学习笔记 tags with Notes.

This would be a very useful tool. Oh my god, I finally made it!

References



Author: Mike Lyou
Link: https://blog.mikelyou.com/2020/01/06/python-learning-09-simple-application/
Liscense: