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

myf*_*me1 2 python shutil

我正在尝试使用shutilPython复制目录树。

我这样做:

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

其中source是源目录的路径targetsource是将要在其中进行复制的不存在目录的名称。

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

根据我在文档中的理解,最后一个参数应该是一个函数,它输入两个参数并返回将从副本中排除的文件名列表。第一个输入是当前目录的名称,以shutil递归方式遍历树,第二个输入是其内容列表。

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

但这是行不通的。它正在复制一切。

我哪里糊涂了?


我想做的是,如果我有

source\
  subdir1\
     file11.txt
     file12.txt
  subdir2\
     file21.txt
Run Code Online (Sandbox Code Playgroud)

我想获得

target\
  subdir1\
  subdir2\
Run Code Online (Sandbox Code Playgroud)

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

dor*_*oru 5

这有什么改变吗?

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))]
Run Code Online (Sandbox Code Playgroud)

  • 我明白了,文件列表需要完整路径。通过 `os.path.isdir` 更改 `is_dir` 是有效的。 (2认同)