天天看點

python複制時不覆寫重命名

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)