欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python实现批量更改xml文件中内容替换

程序员文章站 2022-04-18 19:55:09
...
import os
import io
#paths文件目录,files保存文件路径以及名字
paths='/home/xiaobumidm/Yolo_mark-master/VOC数据集/VOC/'
files=[]
oldStr='basstom'
newStr='base>custom'
for file in os.listdir(paths):
    if file.endswith('.xml'):
        files.append(paths+file)
for file in files:
    with open(file, "r", encoding="utf-8") as f:
        lines=f.readlnes()#将文件内容保存到内存
    with open(file, "w", encoding="utf-8") as f_w:
        for line in lines:#将内存中的文件逐行读取
            if oldStr in line:
                line=line.replace(oldStr,newStr)#新内容代替旧内容
            f_w.write(line)

参考链接:https://www.cnblogs.com/bigberg/p/6489043.html