import os strDir=r'E:\path\synth' f1=open(r'E:\path\synth\train.txt','w') for dirpath, dirnames, filenames in os.walk(strDir): for f in filenames: vf=os.path.join(dirpath,f) p=vf.find('\\') + 1 vlab=f.split('_') if len(vlab) > 1: print(vf[p:] + ' ' + vlab[1] ) str = vf[p:] + ' ' + vlab[1] + '\n' str=str.replace('\\','/') # Linux 格式 f1.writelines(str) f1.close()
txt文件格式如下
![](https://i-blog.csdnimg.cn/blog_migrate/14e4c0a05708f3f2da1981ad1661c6bb.png)