python batch modify the number of categories in the txt file, batch modify the file name

When working on engineering projects, it is often encountered that two datasets need to be merged into one dataset, but the number of categories in the two datasets must be able to correspond. For example, both datasets are binary-classified. The category labels are 0 and 1. In this case, the labels of the other dataset need to be changed to 2 and 3, so that the two datasets can be merged into one.

You can directly use the code directly, replace it with your own path and the category you want to modify.

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)

Batch modification of file names is also an operation that is often encountered in fusion datasets.

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)

Guess you like

Origin blog.csdn.net/zqt321/article/details/122536211