批量替换字符串的python实现

作者:朱金灿
来源:clever101的专栏

问题描述

  最近在编译glut库,发现很多makefile文件需要批量替代字符串,于是就用python写了一个工具程序实现批量替代字符串。

问题解决

  这个功能主要涉及两个函数:遍历指定目录下的指定后缀的文件和对单个文件进行字符串替换。代码实现如下:

#!/usr/bin/python
# -*- coding=utf-8 -*-
# author : clever101@163.com
# date: 2022-05-30
# version: 0.1
#propose:遍历文件夹中在多个文本文件中替换字符串
#参考文献:
#Python实践:一键批量替换不同文本字符串
#https://blog.csdn.net/qq_17256689/article/details/123485731

import sys
import os

# repalce str_a with str_b
def file_process(file_path, a, b):
    print(file_path)
    lens = len(a)
    f = open(file_path, 'r+', encoding='utf-8')
    all_the_lines = f.readlines()
    f.seek(0)  # 移动文件指针,到最开始处
    f.truncate()      # 从当前位置起,往后所有数据进行截断删除
    for line in all_the_lines:
        for i in range(lens):
            line = line.replace(a[i], b[i])
        f.write(line)  # 向文件中按行写入替换后的文本
    f.close()
    return


# mode 0/1
# 0表示老到新,1表示新到老,其他则报错提示
# suffix表示指定后缀
def typedef_switch(dirc, old_type, new_type, mode,suffix):
    if mode != 0 and mode != 1:
        print('Mode set error, mode={}'.format(mode))
        return

    a = []
    b = []
    if mode == 0:
        a = old_type
        b = new_type
    else:
        b = old_type
        a = new_type

    filelist = os.listdir(dirc)
    for file in filelist:
        file_path = os.path.join(dirc, file)
        if os.path.isfile(file_path):
            if os.path.splitext(file_path)[1] == suffix:
                file_process(file_path, a, b)
        elif os.path.isdir(file_path):
            typedef_switch(file_path, old_type, new_type, mode, suffix)

if __name__ == '__main__':
    # an example
    old_type = ['!include <win32.mak>']
    #old_type = ['123456789']
    #输入\\要进行特别处理
    new_type = ['!include <C:\\\\Program Files (x86)\\\\Microsoft SDKs\\\\Windows\\\\v7.1A\\\\Include\\\\Win32.mak>']
    #new_type = ['aaa']
    pathFolder = r'D:\MyProject\publish\glut-3.7'
    #pathFolder = r'D:\MyProject\publish\test'
    typedef_switch(pathFolder, old_type, new_type, 0,'.win')
    print('done!')

    # 正式退出main函数进程,以免main函数空跑
    sys.exit()

参考文献

1.Python实践:一键批量替换不同文本字符串

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2022年6月1日 上午11:53
下一篇 2022年6月1日 上午11:55

相关推荐