python批量修改txt文件里的类别数,批量修改文件名

做工程项目时,经常会遇到需要将两个数据集融合到一个数据集里的情况,但是两个数据集里的类别数又要能够对应上,比如两个数据集都是二分类的,那类别标签就是0和1,这种情况下就需要将另一个数据集的标签改为2和3,这样才能将两个数据集融合到一个里面。

直接上代码,更换成自己的路径和自己想要修改的类别就可以直接用。

def modify_txt(oldtxt_path):
    for oldtxt in os.listdir(oldtxt_path):
        b = []
        txt_root=os.path.join(oldtxt_path+oldtxt)
        with open(txt_root,'r',encoding='utf-8') as f:
            _txt=f.readlines()# 读取所有行,readlines返回的是列表
            for i in _txt:
                b.append(i.split(' '))  #以空格分开
                for x in b:
                    if x[0]=='2':  #这里换成你想要改的类别
                        x[0]='1'
                #print(b)
            with open(txt_root,'w+',encoding='utf-8') as f: #把列表b里的信息再重新写入
                for c in b:
                    f.writelines(' '.join(c))
main:
 p=''#换成自己的路径,路径中不要出现中文,否则无法识别
    modify_txt(p)

批量修改文件名,也是融合数据集经常会遇到的操作。

def rename_dir(path): #批量修改文件名
    for i in os.listdir(path):
        old_path=path+i
        new_path=path+'clothes'+i  #这里我是要修改原文件名所有都加上clothes,根据自己需要可以换掉
        os.rename(old_path,new_path)  #rename,传入的两个参数分别是未改名前的路径和改名后的路径
main:
p=''#换成自己的路径,路径中不要出现中文,否则无法识别
    rename_dir(p)

猜你喜欢

转载自blog.csdn.net/zqt321/article/details/122536211
今日推荐