Python Shuutil.copy 如果我有一个重复的文件,它会复制到新位置

Jac*_*ker 6 python shutil

我正在使用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)
Run Code Online (Sandbox Code Playgroud)

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

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

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

Gal*_*all 13

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

在这里,'_number'在扩展名之前插入 a 以在重复的情况下生成唯一的目标名称。喜欢'foo_1.txt'