在已经存在的目录名后添加数字

问题描述

对于我的 QGIS 插件,我想编写一个 python 脚本,如果该目录已经存在,那么当您多次下载同一个文件时,该目录已经存在,就像 Windows 所做的那样。但我不知道如何实现这一点。

例如:

如果目录 'C:/Dossier' 已存在,则新目录将为 'C:/Dossier(1)' ,依此类推。

提前致谢。

解决方法

我认为您需要这样的东西,其中 path_to_dir 是您要创建的目标。

 import os
 count=0
 if os.path.exists(path_to_dir):
     # start while (adding "(count)" to string)
     while True:
         new_dir_name=path_to_dir+f'({count})'
         if os.path.exists(new_dir_name):
             count+=1
         else:
             os.mkdir(new_dir_name)
             break
 else:
     os.mkdir(path_to_dir)