python 文件操作記錄

#!/usr/bin/env python
# coding=utf-8

import os
import shutil

def getimagepath(path):
    file=open(path)
    data=file.read()
    lines=data.replace(',',' ').replace('\t',' ').split('\n')
    lines=[[ v.strip() for v in line.split(' ') if v.strip()!=''] for line in lines if len(line)>0 and line[0]!='#']
    res=[line[0] for line in lines if line[1]=='1']
    return res




cwd=os.getcwd()
print cwd

txtpath=cwd+'/ImageSets/Main/'
print txtpath

txtlist=os.listdir(txtpath)
namelist=[]
#print txtlist
for name in txtlist:
    index=name.find('_')
    if index!=-1:
        namelist.append(name[:index])
namelist=list(set(namelist))
print len(namelist),'\n',namelist

newfolds=cwd+'/VOC'
oldfolds=cwd+'/JPEGImages'
if not os.path.exists(newfolds):
    os.mkdir(newfolds)

datasets=['train','trainval','val']
for ds in datasets:
    if not os.path.exists(newfolds+'/'+ds):
        os.mkdir(newfolds+'/'+ds)
    for name in namelist:
        if not os.path.exists(newfolds+'/'+ds+'/'+name):
            os.mkdir(newfolds+'/'+ds+'/'+name)
        train_imagepath=getimagepath(txtpath+'/'+name+'_'+ds+'.txt')
        if len(train_imagepath)<=0:  
            print "error in getimagepath ",txtpath+'/'+name+'_'+ds+'.txt'
            exit(0)
        for image in train_imagepath:
            shutil.copyfile(oldfolds+'/'+image+'.jpg',newfolds+'/'+ds+'/'+name+'/'+image+'.jpg')






















 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章