【Python】【完整代码】秀!巧用Python实现对单个文件或多个文件中的指定字符串进行批量修改/替换(超详细)

目录

1. 对单份文件

1.1 将替换后的内容保存到新文件中

1.2 直接替换当前文件中的字符

2. 对多份文件(支持递归子目录)


1. 对单份文件

示例:将文件中字符串“address”替换成“device.address”

1.1 将替换后的内容保存到新文件中

实现代码

#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File : Replace_String_of_Files.py
@Time : 2024/01/28 13:20:44
@Author : Admin 
@Version : 1.0
@Software: Visual Studio Code
'''

import re

def new_file(): 
    f1 = open('/home/old.txt','r+')
    f2 = open('/home/new.txt','w+')
    str1 = r'address'
    str2 = r'device.address'
    for i in f1.readlines():
        k = re.sub(str1,str2,i)
        f2.write(k)
    f1.close()
    f2.close()

if __name__ == '__main__':
    new_file()

1.2 直接替换当前文件中的字符

代码思路设计如下:

先以只读模式打开后,对文件每一行进行readlines()操作,并保存到新的列表中。然后随之关闭。 再以'w+'方式进行读写打开,对已经保存的列表用re.sub()进行替换操作,并用f.writelines()函数写入。

实现代码

#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File : Replace_string_of_Single_files.py
@Time : 2024/01/28 14:28:30
@Author : Admin 
@Version : 1.0
@Software: Visual Studio Code
'''

import re

def new_file():
    f = open('/home/mac.txt','r')
    alllines=f.readlines()
    f.close()
    f = open('/home/mac.txt','w+')
    for i in alllines:
        k = re.sub('address','device.address',i)
        f.writelines(k)
    f.close()


if __name__ == '__main__':
    new_file()

2. 对多份文件(支持递归子目录)

代码思路设计如下:

结合os模块,依次读入文件夹路径,子文件夹路径,文件路径,然后使用for循环,对每份文件进行遍历,然后执行读入文件、替换字符串、重新写入文件的操作。

示例:要求实现指定文件夹下,所有子文件夹中文件的字符串“address”替换成“device.address”

实现代码

#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File : Replace_string_of_Multiple_files.py
@Time : 2024/01/28 17:47:13
@Author : Admin
@Version : 1.0
@Software: Visual Studio Code

该函数实现批量读入文件,并寻找替换某个字符串,将修改后的字符串重新写入文件
file_PATH: 主文件夹路径
folder_path:子文件夹路径
file_path:文件路径
old_str: 待修改的字符串
new_str:修改后的字符串
'''

import os

def new_file(file_PATH,old_str,new_str):
    folder_list=os.listdir(file_PATH)#文件夹下的子文件夹列表
    for folder in folder_list:
        folder_path=os.path.join(file_PATH,folder)#子文件夹路径
        file_list=os.listdir(folder_path)#子文件夹下的文件列表
        for file in file_list:
            file_path=os.path.join(folder_path,file)#文件路径
            with open(file_path, "r", encoding='utf-8') as f:  # 以只读方式打开文件
                data = f.read()  # 读取文件,读取为一个字符串
                str_replace = data.replace(old_str,new_str)#将字符串中的某个字符进行替换
                with open(file_path, "w", encoding='utf-8') as f:#重新打开文件,选择写入模式
                    f.write(str_replace)      # 将修改后的字符串重新写入文件
#函数执行
if __name__ == "__main__":
    file_PATH=r'E:\project_file\string\'
    old_str="address"
    new_str="device.address"
    new_file(file_PATH=file_PATH,old_str=old_str,new_str=new_str)

你可能感兴趣的:(python,开发语言,ipython,pytest,自动化,运维开发)