I'm trying use shutil.copytree:
shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=None)
This copy also files in folder. I need copy only folders without ANY files. How to do it?
Method 1: Using shutil. copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. The destination directory, named by (dst) must not already exist. It will be created during copying. It takes an optional argument which is “ignore”.
While shutil. copy() will copy a single file, shutil. copytree() will copy an entire folder and every folder and file contained in it.
The shutil. copy2() method is identical to shutil. copy() except that copy2() attempts to preserve file metadata as well.
You can do that by providing a "ignore" function
def ig_f(dir, files):
return [f for f in files if os.path.isfile(os.path.join(dir, f))]
shutil.copytree(SRC, DES, ignore=ig_f)
Basically, when you call copytree, it will recursively go to each child folder and provide a list of files in that folder to the ignore function to check if those files are suitable based on a pattern. The ignored files will be returned as a list in the end of the function and then, copytree will only copy items excluding from that list (which in your case, contains all the files in the current folder)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With