您可以使用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

list_dir = folder1 = mntdisk1lhlandmarkdata3上海新天地folder2 = mntdisk1lhlandmarkdata3上海石库门target_dir = mntdisk1lhlandmarkdata2compare_imagesfolder1 folder2if not ospathexiststarget_dir osmakedirstarge

原文地址: http://www.cveoy.top/t/topic/ib9G 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录