原文链接:【Python】如何在文件夹里批量替换文本中的内容?_YaoYee_7的博客-CSDN博客
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 21 2022
@author: MMG
"""
# coding=utf-8
import os
path = "D:\\Download\\LiDAR_data\\object\\training\\label_2"
def listfiles(dirpath):
filelist = []
for root, dirs, files in os.walk(dirpath):
for fileObj in files:
filelist.append(os.path.join(root, fileObj))
return filelist
## 此函数可以不需要
def txt_modify(files):
for file in files:
label_path = os.path.join(path, file)
with open(label_path, 'r+') as f:
lines = f.readlines()
for line in lines:
# e.g.'Bus' is the new one, Truck is the old one
f.seek(0)
f.truncate()
f.write(line.replace('Truck', 'Bus'))
# f.write(line.replace('dog', 'cat').replace('man', 'boy')) # 多个内容的替换
f.close()
def main():
filelist = listfiles(path)
for fileobj in filelist:
f = open(fileobj, 'r+')
lines = f.readlines()
f.seek(0)
f.truncate()
for line in lines:
f.write(line.replace('Truck', 'Bus'))
f.close()
if __name__ == main():
main()