如何在目标目录已存在同名文件夹时创建带编号新文件夹
解决重复复制文件夹时自动生成带编号目录的问题
Got it, let's fix this frustrating issue where your script fails when the backup folder already exists. The core problem here is that shutil.copytree throws an error if the target directory already exists—so we need to add logic to automatically find the next available numbered folder name before running the copy.
解决方案思路
We'll build a helper function that:
- Starts with your base backup name (e.g.,
Backupinstead of hardcodingBackup1) - Checks if a folder with that name plus a number exists (starting at 1)
- Keeps incrementing the number until it finds a folder name that doesn't exist yet
- Uses that unique name for the copy operation
完整代码示例
import shutil import os # 源目录和备份基础名称(去掉固定的编号) MAIN_DIR = r'Y:\A' BASE_BACKUP_NAME = r'Y:\B\Backup' def get_unique_backup_path(base_name): counter = 1 while True: # 拼接带编号的目标路径 target_path = f"{base_name}{counter}" # 检查该路径是否已经是一个文件夹(避免和同名文件冲突) if not os.path.isdir(target_path): return target_path counter += 1 # 获取可用的唯一备份路径 target_dir = get_unique_backup_path(BASE_BACKUP_NAME) # 执行文件夹复制 shutil.copytree(MAIN_DIR, target_dir) print(f"备份完成!文件夹已复制到: {target_dir}")
代码解释
get_unique_backup_path函数: This is the key part. It starts atBackup1, checks if that folder exists. If yes, it triesBackup2, and so on until it finds a name that's not taken.os.path.isdir: We use this instead ofos.path.existsto make sure we're only checking for folders—this avoids conflicts if there's a file with the same name as our intended backup folder.- Dynamic target path: By generating the target path on the fly, you can run this script as many times as you want, and it'll always create a new numbered backup without failing.
额外优化建议
If you want to start with just Backup (without a number) for the first run, you can adjust the helper function like this:
def get_unique_backup_path(base_name): # 先检查基础名称本身是否可用 if not os.path.isdir(base_name): return base_name # 如果基础名称已存在,再开始加编号 counter = 1 while True: target_path = f"{base_name}{counter}" if not os.path.isdir(target_path): return target_path counter += 1
This way, your first backup goes to Backup, the second to Backup1, third to Backup2, etc.
内容的提问来源于stack exchange,提问作者kytexaranort
相关产品推荐
相关产品推荐

