以下是用 Python 实现批量替换 .xml 文件指定行内容的代码:

import os

# 定义要替换的行数范围
start_line = 4
end_line = 7

# 定义要替换成的内容
replacement_text = '八嘎牙路'

# 定义要遍历的目录路径
directory_path = '/path/to/directory'

# 遍历目录下所有文件
for file_name in os.listdir(directory_path):
    # 判断文件是否以.xml结尾
    if file_name.endswith('.xml'):
        # 打开文件进行替换
        with open(os.path.join(directory_path, file_name), 'r+') as file:
            # 读取文件内容
            file_lines = file.readlines()
            # 替换指定行的内容
            for i in range(start_line-1, end_line):
                file_lines[i] = replacement_text + '\n'
            # 将替换后的内容写回文件
            file.seek(0)
            file.writelines(file_lines)
            file.truncate()

该代码会遍历指定目录下所有以 .xml 结尾的文件,并对每个文件的第 4-7 行进行替换。如果想要替换其他行数的内容,只需要修改 start_lineend_line 的值即可。同时,也可以修改 replacement_text 的值来指定替换成的内容。

Python 脚本:批量替换 XML 文件指定行内容

原文地址: https://www.cveoy.top/t/topic/n7nd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录