EADST

Copy and Rename File When Existing Same Name

Python: Copy and Rename File When Existing Same Name

import os
import shutil

def rename_copy(file_path, out_dir):
    name = os.path.basename(file_path)
    if not os.path.exists(os.path.join(out_dir, name)):
        save_path = os.path.join(out_dir, name)
        shutil.copy(file_path, save_path)
    else:
        base, extension = os.path.splitext(name)
        print(base, extension)
        i = 1
        while os.path.exists(os.path.join(out_dir, '{}_{}{}'.format(base, i, extension))):
            i += 1
        save_path = os.path.join(out_dir, '{}_{}{}'.format(base, i, extension))
        shutil.copy(file_path, save_path)
    return save_path

path = "./copy/"
input_path = "test.jpg"
print(path, safe_copy(input_path, path))
相关标签
About Me
XD
Goals determine what you are going to be.
Category
标签云
站点统计

本站现有博文266篇,共被浏览440780

本站已经建立2019天!

热门文章
文章归档
回到顶部