我有一个定期创建新目录的脚本。我想检查它是否已经存在,如果是,则将现有文件夹移动到备份。我的第一次迭代是
if os.path.isdir(destination_path):
os.rename(destination_path,destination_path + '_old')
但是,如果已经有一个备份,它肯定会崩溃。我想要做的是找到与destination_path匹配的目录数,并将该数字附加到版本号。
if os.path.isdir(destination_path):
n = get_num_folders_like(destination_path)
os.rename(destination_path,destination_path + str(n))
我只是不确定如何制作这样一个假设的功能。我认为fnmatch可能有用,但我无法正确使用语法。
答案 0 :(得分:1)
如果您需要将旧目录移到一边,可以通过以相同名称列出所有目录,然后通过从匹配名称中提取数字最大值来选择最后一个目录,从而轻松完成重新编号。
列出目录可以使用glob
module;它将列表文件与fnmatch
模块结合起来进行过滤:
import glob
if os.path.isdir(destination_path):
# match all paths starting with the destination name, plus at least
# an underscore and one digit.
backups = glob.glob(destination_path + '_[0_9]*')
def extract_number(path):
try:
# assume everything after `_` is a number
return int(path.rpartition('_')[-1])
except ValueError:
# not everything was a number, skip this directory
return None
backup_numbers = (extract__number(b) for b in backups)
try:
next_backup = max(filter(None, backup_numbers)) + 1
except ValueError:
# no backup directories
next_backup = 1
os.rename(destination_path,destination_path + '_{:d}'.format(next_backup))
我假设你并不担心这里的竞争状况。
答案 1 :(得分:0)
根据给出的更一般的答案,我最终使用了针对我的特定情况更简化的内容
if os.path.isdir(destination_path):
n = len(glob.glob(destination_path + '*'))
os.rename(destination_path, destination_path + '_' + str(n))