gpt4 book ai didi

python - 在 python 中复制时排除一些子文件夹(我使用 copytree)

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:16 27 4
gpt4 key购买 nike

我正在尝试执行 DIR-COPY。我的输入是这样的..

    source = D/Test/Source
Target = D/Test/Target
Ignore_Pattern = '*.exe'
Exclude_Sub_Folder = D/Test/Source/Backup,D/Test/Source/Backup2

我可以使用 copytree 中的忽略属性忽略 .exe 文件喜欢这个

    shutil.copytree(source , Target ,ignore=shutil.ignore_patterns(Ignore_Pattern)) 

我不确定如何排除源目录中的一些子文件夹。

请帮忙......

谢谢

最佳答案

您可以忽略所有名称为 Backup 或 Backup2 的文件夹:

shutil.copytree(source , Target ,ignore=shutil.ignore_patterns(Ignore_Pattern, "Backup", "Backup2"))

“但是我有多个名为‘Backup’的文件夹,我特别想只忽略 Test/Source 目录中的那个”,您说。在这种情况下,您需要提供一个自定义忽略函数来调查完整路径。

to_exclude = ["D:/Test/Source/Backup", "D:/Test/Source/Backup2"]

#ignores excluded directories and .exe files
def get_ignored(path, filenames):
ret = []
for filename in filenames:
if os.path.join(path, filename) in to_exclude:
ret.append(filename)
elif filename.endswith(".exe"):
ret.append(filename)
return ret

shutil.copytree(source , Target ,ignore=get_ignored)

(注意在 to_exclude 中为您的特定操作系统使用正确的路径分隔符。您不希望包含“Test\Source\Backup”,因为您使用了错误的斜线。)

关于python - 在 python 中复制时排除一些子文件夹(我使用 copytree),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28985921/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com