在 Python 中使用 shutil 仅复制目录树中的目录

Copy only directories in a directory tree using shutil in Python

我正在尝试使用 Python 中的 shutil 复制目录树。

我是这样做的:

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

其中 source 是源目录的路径,target 是一个不存在的目录的名称,source 的副本将在该目录中发生。

第三个参数表示对符号链接的处理。

根据我在 documentation 中的理解,最后一个参数应该是一个输入两个参数的函数和 returns 将从副本中排除的文件名列表。第一个输入是当前目录的名称,因为 shutil 递归遍历树,第二个输入是其内容列表。

这就是为什么我输入一个 lambda 试图 return 列表中的那些文件元素。

但这不起作用。它正在复制一切。

我哪里搞糊涂了?


我想做的是,如果我有

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

我想获得

target\
  subdir1\
  subdir2\

顺便说一句,我想我可以使用 walkglob 自己编写副本,但我认为 shutil 使用起来会很简单。

这有什么改变吗?

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))]

有趣的发现,试试这个:

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

阅读 this post 之后,问题似乎是 r 不被 isfile 理解,直到你有一个完整的路径,我通过添加 x+os.sep+r 来重建它.