神剑山庄资源网 Design By www.hcban.com

一、介绍

在做YOLOv3项目时,会需要将文本文件中的某部分内容进行批量替换和修改,所以编写了python程序批量替换所有文本文件中特定部分的内容。

二、代码实现

import re
import os
 
 
def reset():
 
  i= 0
  path = r"/data/sdxx/mzq/YOLOv3/YOLOv3-New-fire/YOLOv3-SaveVideo-New/scripts/VOCdevkit/VOC2019/labels/"
  filelist = os.listdir(path)  # 该文件夹下所有文件(包括文件夹)
  for files in filelist: # 遍历所有文件
    i = i + 1
    Olddir = os.path.join(path,files); # 原来的文件路径
    if os.path.isdir(Olddir):
      continue;
 
    filename = os.path.splitext(files)[0];
    filetype = os.path.splitext(files)[1];
    filePath = path+filename+filetype
 
    alter(filePath,"16","1")
 
def alter(file,old_str,new_str):
 
  with open(file,"r",encoding="utf-8") as f1,open("%s.bak"% file,"w",encoding="utf-8") as f2:
    for line in f1:
 
 
      if old_str in line:
        line = line.replace(old_str,new_str)
 
      f2.write(line)
 
  os.remove(file)
  os.rename("%s.bak" % file,file)
 
reset()

以上这篇python 实现批量替换文本中的某部分内容就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

标签:
python,批量,替换,文本

神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网 免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com

评论“python 实现批量替换文本中的某部分内容”

暂无python 实现批量替换文本中的某部分内容的评论...