Python shutil.copytree: 如何在目标文件夹已存在时避免报错

当使用 shutil.copytree 函数复制文件夹时,如果目标文件夹已经存在,就会引发错误。为了解决这个问题,可以使用 shutil.rmtree 先删除目标文件夹,然后再调用 shutil.copytree 进行复制。

以下是一个示例代码:

import shutil
import os

def copytree_no_error(src, dst):
    if os.path.exists(dst):
        shutil.rmtree(dst)
    shutil.copytree(src, dst)

copytree_no_error('WhereHelper.lang_where', 'WhereHelper.lang_to')

在这个代码中,我们首先使用 os.path.exists 检查目标文件夹是否存在。如果存在,则使用 shutil.rmtree 删除目标文件夹。然后,我们调用 shutil.copytree 函数进行复制操作。

这样,即使目标文件夹已经存在,也不会报错,代码可以顺利执行。

Python shutil.copytree: 如何在目标文件夹已存在时避免报错

原文地址: https://www.cveoy.top/t/topic/phYV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录