python創建文件夾(解決重復文件夾)


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM