2025年2月22日 星期六 甲辰(龙)年 腊月廿二 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

python创建文件夹(解决重复文件夹)

时间:09-12来源:作者:点击数:23

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
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门