python修改文件名

修改图片的文件名,并将修改的文件名保存到相应的文件夹中。

# -*- coding: utf-8 -*-
"""
Created on Sun May 26 18:17:40 2019

@author: Administrator
"""

#!/usr/bin/env python
 # -*- coding:utf-8 -*-
import os

root = os.getcwd() #获取当前路径
data = 'JPEGImages'  #101数据集的文件夹名称 JPEGImages  Annotations
path = os.listdir(root+'/'+ data) #显示该路径下所有文件
path.sort()
vp = 1 #测试集合取总数据前10% 0.1
#ftr = open('train.txt','w')
fva = open('test.txt','w')
i = 1

for line in path:
     subdir = root+'/'+ data +'/'+line
     childpath = os.listdir(subdir)
     #print(childpath)
     mid = int(vp*len(childpath))
     for child in childpath[:mid]:
     	 #print(line)
         #去掉jpg后缀
         #child = child.strip('.jpg')
         #修改文件名
         src = os.path.join(os.path.abspath(subdir), child)
         subpath = line + child ;#data+'/'+ + ' ' str(i) 
         dst = os.path.join(os.path.abspath(subdir), subpath)
 		 #修改文件写在txt文件上的名
         #child = child.strip(line)
         #child = child.strip('.xml')
         
         t = line + child
         os.rename(src, dst) #重新命名
         fva.write(t +'\n')
     """for child in childpath[mid:]:
         child = child.strip('.jpg')
         subpath =  child ;#data+'/'+  + ' '+ line
         d = ' %s' %(i)
         t =  subpath # + d
         ftr.write(t +'\n') #"""
     i=i+1

#ftr.close()  #关闭文件流
fva.close()   

你可能感兴趣的:(程序)