I want to copy some folders and files from a path to another path. for example, I want to copy the folder(called folder1) which has some other subfolders and some files inside itself to another folder(dst). In my program, at the first, I want to check if there is a folder named folder1 in destination folder and if not, create a folder with folder1 name and then copy the content of folder1 to target. In addition, maybe we have folder1 in the target path, but there are some subfolders of folder1 which don't exist in target and we must use a recursive function for that. Here is my recursive function for this purpose:
def CopyFol_Subfolders(src, src_folder, dst):
Dir = next(os.walk(src))[1]
sub_files = ""
sub_files = next(os.walk(src))[2]
if not os.path.exists(dst + "/" + src_folder):
os.makedirs(dst + "/" + src_folder)
shutil.copy2(src + "/" + src_folder, dst + "/" + src_folder)
elif os.path.exists(src + "/" + src_folder) and is_exist_file(src+"/"+src_folder,dst+"/"+src_folder,sub_files):
copy_files(sub_files, src+"/"+src_folder, dst+"/"+src_folder)
else:
subfolders = ""
subfolders = next(os.walk(src + "/" + src_folder+"/"))[1]
for folder in subfolders:
CopyFol_Subfolders(src + "/" + src_folder, folder, dst + "/" + src_folder)
the copy_files function will copy the files from src +"/"+src_folder to dst+"/"+src_folder
I be confused and this does not work. I got different errors in shutil.copy2 which tell me x is not a file or x is a directory.
Can please some one check logic of my recursive function and let me know what is this problem?
解决方案
Use os.path.isdir instead of os.path.exists to ensure that it can only be a directory not a file. And os.path.join is better than concatenating path strings by ourselves.
def CopyFol_Subfolders(src, dst):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
CopyFol_Subfolders(s, d)
else:
shutil.copy2(s, d)