1. copy_sub_folders.py
import os from os import walk import shutil olddir = '/data/share/xxx_face/identities_13/' newdir = './13/' shutil.copytree(olddir,newdir)
2. remove_files_in_subfolder.py
import os from os import walk import shutil mypath='./13/' for (dirpath, dirnames, filenames) in walk(mypath): for dir in dirnames: for (dirpath1, dirnames1, filenames1) in walk(mypath+dir): for i in filenames1: # print(mypath+dir+'/'+i) os.remove(mypath+dir+'/'+i)
3. combine step1 and step2, copy_subfolder_remove_itsfile.py
import os from os import walk import shutil olddir = './identities_12/' newdir = './12/' shutil.copytree(olddir,newdir) for (dirpath, dirnames, filenames) in walk(newdir): for dir in dirnames: for (dirpath1, dirnames1, filenames1) in walk(newdir+dir): for i in filenames1: print(newdir+dir+'/'+i) os.remove(newdir+dir+'/'+i)
4. or generate the sub-folders directly (copy_subfolder_remove_itsfile.py)
import os from os import walk import shutil olddir = './identities_11/' newdir = './11/' ''' try: os.mkdir(newdir) except OSError: if not os.path.isdir(newdir): raise ''' for (dirpath, dirnames, filenames) in walk(olddir): os.mkdir(newdir+dirpath.split('/')[2],0755)
5. Improve script 4 with sys.argv
#!/usr/bin/python import os import sys from os import walk import shutil if len(sys.argv) != 2: print( "Original image folder is identities_xxx. " "This script will mkdir folder xxx and generate all of its subfolders. " "For example, make folder 1 according to identities_1 , then run: " " python 4_copy_subfolder_remove_itsfile.py 1 ") exit() folder_number = sys.argv[1] olddir = "./identities_"+folder_number+"/" newdir = "./"+folder_number+"/" print olddir print newdir ''' try: os.mkdir(newdir) except OSError: if not os.path.isdir(newdir): raise ''' for (dirpath, dirnames, filenames) in walk(olddir): os.mkdir(newdir+dirpath.split('/')[2],0755)