Copy and Rename File When Existing Same Name
作者:XD / 发表: 2022年3月2日 06:13 / 更新: 2022年3月2日 06:13 / 编程笔记 / 阅读量:1437
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))
相关标签