要同时对多个txt文件的内容进行替换,可以使用Python的os和fileinput模块。下面是一个示例代码:

import os
import fileinput

# 指定文件夹路径
folder_path = r'C:\Users\jh\Desktop\data\input\labels'

# 要替换的内容和替换后的内容
old_text = 'old_text'
new_text = 'new_text'

# 遍历文件夹下的所有txt文件
for file_name in os.listdir(folder_path):
    if file_name.endswith('.txt'):
        file_path = os.path.join(folder_path, file_name)
        
        # 使用fileinput模块打开文件并进行替换
        with fileinput.FileInput(file_path, inplace=True) as file:
            for line in file:
                # 替换内容
                line = line.replace(old_text, new_text)
                # 输出替换后的内容到文件
                print(line, end="")

请注意,这段代码会直接修改原始文件,请确保在运行代码之前备份好原始文件,以防止意外修改。


原文地址: https://www.cveoy.top/t/topic/pmqO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录