Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shutil.copytree without files

Tags:

python

shutil

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?

like image 819
user2216451 Avatar asked Mar 27 '13 16:03

user2216451


People also ask

How do you copy a directory structure without files in Python?

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”.

What is the difference between Shutil copy () and Shutil Copytree ()?

While shutil. copy() will copy a single file, shutil. copytree() will copy an entire folder and every folder and file contained in it.

What is difference between Shutil copy and copy2?

The shutil. copy2() method is identical to shutil. copy() except that copy2() attempts to preserve file metadata as well.


1 Answers

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)

like image 181
Thai Tran Avatar answered Sep 17 '22 13:09

Thai Tran