Python 文件移动重命名:解决 shutil.Error: Destination path already exists
在 Python 中使用 shutil.move() 函数移动文件时,如果目标路径已存在同名文件,就会抛出 shutil.Error: Destination path already exists 的错误。
为了解决这个问题,您可以使用 os.path.basename() 函数获取文件名,然后将其与目标目录路径进行拼接,从而生成新的文件路径。以下是修改后的代码示例:
import os
import shutil
list_dir = []
folder1 = '/mnt/disk1/lh/landmark/data3/上海新天地'
folder2 = '/mnt/disk1/lh/landmark/data3/上海石库门'
target_dir = '/mnt/disk1/lh/landmark/data2/'
compare_images(folder1, folder2)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
# 根据列表中的路径将文件移动到目标目录
for file_path in list_dir:
file_name = os.path.basename(file_path)
new_file_path = os.path.join(target_dir, file_name)
if os.path.exists(new_file_path):
# 如果目标路径已存在同名文件,则在文件名后添加数字序号
file_name, file_ext = os.path.splitext(file_name)
index = 2
while os.path.exists(new_file_path):
new_file_name = f'{file_name}{index}{file_ext}'
new_file_path = os.path.join(target_dir, new_file_name)
index += 1
shutil.move(file_path, new_file_path)
compare_images(folder1, folder2)
这样,如果目标路径已存在同名文件,将会在文件名后添加数字序号。例如,'2.jpeg'将会被重命名为'上海新天地2.jpeg'。
原文地址: https://www.cveoy.top/t/topic/pURt 著作权归作者所有。请勿转载和采集!