I am pretty new to using python and am trying to create a new folder structure for some files. I am using os, shutil, and copytree to do the following:
ORIGINAL FOLDER STRUCTURE:
top_folder/
batch1/
1.tif
1.xml
2.tif
2.xml
hello.tif
hello.xml
batch2/
purple.tif
purple.xml
red.tif
red.xml
RESULTING FOLDER STRUCTURE:
top_folder/
batch1/
1/
1.tif
1.xml
2/
2.tif
2.xml
hello/
hello.tif
hello.xml
batch2/
purple/
purple.tif
purple.xml
red/
red.tif
red.xml
My question is: how do I use copytree and get it to copy only the first two levels of folders, but then copytree stops and then I have my own code to transform the rest of the folder structure within the batch folders?
Here is my code:
import os, shutil, errno
def copy(src, dest):
try:
shutil.copytree(src, dest)
except OSError as e:
if e.errno == errno.ENOTDIR:
#code here to transform folders
else:
break
else:
print('Directory not copied. Error: %s' % e)
You should be able to use the ignore
argument of copytree
to help with this. Basically you could use it to setup a glob
pattern which includes everything but the directories/files you do want to copy, and then it should match all the others, and thus ignore them. You can create a customized ignore
function to behave as you'd like.
See more details here, including example code: https://docs.python.org/2/library/shutil.html#copytree-example