Python Shutil.copy 如果我有重复文件,它会复制到新位置吗

2024-05-05

我正在与shutil.copypython 中的方法。

我找到了下面列出的定义:

def copyFile(src, dest):
    try:
        shutil.copy(src, dest)
    # eg. src and dest are the same file
    except shutil.Error as e:
        print('Error: %s' % e)
    # eg. source or destination doesn't exist
    except IOError as e:
         print('Error: %s' % e.strerror)

我正在循环内访问定义。该循环基于每次都会更改的字符串。该代码查看目录中的所有文件,如果它在文件中看到字符串的一部分,则会将其复制到新位置

我很确定会有重复的文件。所以我想知道会发生什么。

它们会被复制,还是会失败?


shutil.copy https://docs.python.org/2.7/library/shutil.html?highlight=shutil.copy#shutil.copy不会将文件复制到新位置,而是会覆盖该文件。

将文件 src 复制到文件或目录 dst。如果 dst 是一个目录,创建(或覆盖)与 src 具有相同基本名称的文件在 指定的目录。复制权限位。 src 和 dst 是 以字符串形式给出的路径名。

因此,您必须自行检查目标文件是否存在并根据需要更改目标。例如,您可以使用以下方法来实现安全复制:

def safe_copy(file_path, out_dir, dst = None):
    """Safely copy a file to the specified directory. If a file with the same name already 
    exists, the copied file name is altered to preserve both.

    :param str file_path: Path to the file to copy.
    :param str out_dir: Directory to copy the file into.
    :param str dst: New name for the copied file. If None, use the name of the original
        file.
    """
    name = dst or os.path.basename(file_path)
    if not os.path.exists(os.path.join(out_dir, name)):
        shutil.copy(file_path, os.path.join(out_dir, name))
    else:
        base, extension = os.path.splitext(name)
        i = 1
        while os.path.exists(os.path.join(out_dir, '{}_{}{}'.format(base, i, extension))):
            i += 1
        shutil.copy(file_path, os.path.join(out_dir, '{}_{}{}'.format(base, i, extension)))

Here, a '_number'插入到扩展名之前,以生成唯一的目标名称,以防重复。喜欢'foo_1.txt'.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python Shutil.copy 如果我有重复文件,它会复制到新位置吗 的相关文章

随机推荐