2

I am trying to copy a directory tree using shutil in Python.

I am doing it like this:

shutil.copytree(source,target,False,lambda x,y:[r for r in y if os.path.isfile(r)]);

where source is the path to the source directory, and target is the name for a non-existent directory inside which the copy of source is going to occur.

The third argument indicates the treatment of symbolic links.

The last argument, from what I understood in the documentation should be a function that inputs two parameters and returns a list of file-names that will be excluded from the copy. The first input is the name of the current directory, as shutil travels the tree recursively, and the second the list of its contents.

This is why I input a lambda trying to return those elements in the list that are files.

But this is not working. It is copying everything.

Where am I getting confused?


What I am trying to do is, if I have

source\
  subdir1\
     file11.txt
     file12.txt
  subdir2\
     file21.txt

I want to obtain

target\
  subdir1\
  subdir2\

By the way, I guess I would be able to write the copy myself using walk or glob, but I thought shutil would be straightforward to use.

myfirsttime1
  • 287
  • 2
  • 12

2 Answers2

6

Does this make any change?

shutil.copytree(source,target,symlinks=False,ignore=ignore_files);

def ignore_files(folder, files):
    return [f for f in files if not os.path.isdir(os.path.join(folder, f))]
07lodgeT
  • 108
  • 9
doru
  • 9,022
  • 2
  • 33
  • 43
1

Fun to find out, try this:

shutil.copytree(source,target,False,lambda x,y:[r for r in y if os.path.isfile(x+os.sep+r)]);

After reading this post the problem seems to be that r is not understood by isfile until you have a full path, which I rebuild by adding that x+os.sep+r.

Community
  • 1
  • 1
sal
  • 3,515
  • 1
  • 10
  • 21