^{}不会将文件复制到新位置,它将覆盖该文件。Copy the file src to the file or directory dst. If dst is a directory,
a file with the same basename as src is created (or overwritten) in
the directory specified. Permission bits are copied. src and dst are
path names given as strings.
因此,您必须检查自己是否存在目标文件,并根据需要更改目标。例如,这是可以用来实现安全复制的: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)))
这里,在扩展名之前插入一个'_number',以便在重复的情况下生成唯一的目标名称。就像'foo_1.txt'。