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

yipeiwu_com6年前Python基础

一、介绍

在做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设计】。

相关文章

python3+PyQt5+Qt Designer实现堆叠窗口部件

python3+PyQt5+Qt Designer实现堆叠窗口部件

本文是对《Python Qt GUI快速编程》的第9章的堆叠窗口例子Vehicle Rental用Python3+PyQt5+Qt Designer进行改写。 第一部分无借用Qt De...

python 根据pid杀死相应进程的方法

用python语言实现根据pid杀死相应进程 kill_process.py代码如下 #! /usr/bin/python # -*- coding: utf-8 -*- impo...

实例讲解Python3中abs()函数

Python3 abs() 函数 描述 abs() 函数返回数字的绝对值。 语法 以下是 abs() 方法的语法: abs( x ) 参数 x-- 数值表达式,可以是整数,浮点...

python与caffe改变通道顺序的方法

把通道放在前面: image = cv2.imread(path + file) image = cv2.resize(image, (48, 48), interpolation...

Python3 加密(hashlib和hmac)模块的实现

以下代码以Python3.6.1为例 hashlib : 不可逆加密 hmac : 不可逆键值对方式加密 hashlib模块简介: hashlib模块为不同的安全哈希/安全散...