python创建文件夹(解决重复文件夹)
对于重复的文件夹名,使用A_1,A_2……A_n
- """
- 创建文件夹
- 遇到重复文件夹命名为文件夹目录_1(2,3,4……)
- 返回文件夹目录名称
- """
- def mkdir(path,root_flag=False):
- folder = os.path.exists(path)
- floder_path = path
- if not folder:
- os.makedirs(path)
- # print(path+"---create OK---")
- else:
- if not root_flag:
- num_p = 1
- # parent_path = os.path.dirname(path)
- # base_path = os.path.basename(path)
- sub_path = glob.glob(path + '*')
- if sub_path:
- # 最后一个创建目录
- last_path = sub_path[-1]
- # print(last_path)
- floder_path = last_path + '_{}'.format(num_p)
- if last_path.find('_') > 0:
- num_str = last_path.split('_')
- if num_str[-1].isdigit():
- num_p = int(num_str[-1]) + 1
- floder_path = last_path[0:last_path.rfind(
- '_')] + '_{}'.format(num_p)
- os.makedirs(floder_path)
- else:
- os.makedirs(floder_path)
- else:
- os.makedirs(floder_path)
- # print(path+"---is exists---")
- return floder_path