python复制时不覆盖重命名

python复制时已存在文件,未防止覆盖替换,重命名正在复制到文件。使用递归,将文件C:\Users\lishihang\Desktop\1.txt 拷贝到C:\Users\lishihang\Desktop\新建文件夹 下,命名为1<_copy>*.txt。如下代码:

import os
import shutil
def get_new_name(dir, f):

    if os.path.exists(os.path.join(dir, f)):
        # 拆分文件名和文件后缀,获取新命名
        s="%s_%s%s" % (os.path.splitext(f)[0], "copy", os.path.splitext(f)[1])
        return get_new_name(dir, s)# 新命名文件是否存在
    return os.path.join(dir, f)# 返回新文件路径

p=get_new_name(r"C:\Users\lishihang\Desktop\新建文件夹","1.txt")
shutil.copy(r"C:\Users\lishihang\Desktop\1.txt",p)

猜你喜欢

转载自blog.csdn.net/nima1994/article/details/81182320
今日推荐