python shutil copy_Python Shutil.copy如果我有一个重复的文件,它会复制到新的位置吗...

^{}不会将文件复制到新位置,它将覆盖该文件。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'。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值