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

yipeiwu_com7年前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设计】。

相关文章

Python中使用支持向量机(SVM)算法

Python中使用支持向量机(SVM)算法

在机器学习领域,支持向量机SVM(Support Vector Machine)是一个有监督的学习模型,通常用来进行模式识别、分类(异常值检测)以及回归分析。 其具有以下特征: &n...

Python 可爱的大小写

函数较简单,看下面的例子: 复制代码 代码如下:s = 'hEllo pYthon' print s.upper() print s.lower() print s.capitalize...

python连接PostgreSQL数据库的过程详解

1. 常用模块 # 连接数据库 connect()函数创建一个新的数据库连接对话并返回一个新的连接实例对象 PG_CONF_123 = { 'user':'emma', 'p...

python通过imaplib模块读取gmail里邮件的方法

本文实例讲述了python通过imaplib模块读取gmail里邮件的方法。分享给大家供大家参考。具体实现方法如下: import imaplib mailserver = imap...

python实现用户管理系统

本文实例为大家分享了python实现用户管理系统的具体代码,供大家参考,具体内容如下 《python核心编程》第七章练习题第五题 一、题目描述  userpw2.py。下面的...