要解决将保存在一个文件夹中的附件与保存在不同文件夹中的其他附件混在一起的问题,可以使用以下代码示例:
import os
import shutil
# 定义源文件夹路径
source_folder = 'path_to_source_folder'
# 定义目标文件夹路径
destination_folder = 'path_to_destination_folder'
# 获取源文件夹中的所有文件
files = os.listdir(source_folder)
# 遍历每个文件
for file in files:
# 构建源文件的完整路径
source_file = os.path.join(source_folder, file)
# 构建目标文件的完整路径
destination_file = os.path.join(destination_folder, file)
# 判断文件是否在目标文件夹中存在
if os.path.exists(destination_file):
# 如果存在,给文件一个新的名称,以避免重名
destination_file = os.path.join(destination_folder, 'new_' + file)
# 复制源文件到目标文件夹
shutil.copy(source_file, destination_file)
请将代码中的path_to_source_folder
替换为保存有附件的源文件夹的路径,将path_to_destination_folder
替换为保存其他附件的目标文件夹的路径。代码会将源文件夹中的附件复制到目标文件夹中,并确保不会与目标文件夹中的其他附件重名。
上一篇:保存在XML中的隐藏字符