Python 判斷文件路徑是否存在,不存在創建

def check_and_creat_dir(file_url):
    '''
    判斷文件是否存在,文件路徑不存在則創建文件夾
    :param file_url: 文件路徑,包含文件名
    :return:
    '''
    file_gang_list = file_url.split('/')
    if len(file_gang_list)>1:
        [fname,fename] = os.path.split(file_url)
        print(fname,fename)
        if not os.path.exists(fname):
            os.makedirs(fname)
        else:
            return None
        #還可以直接創建空文件
        
    else:
        return None
check_and_creat_dir('file/vide/dj/data.py')

補充:os.path.split(file_url)返回的是路徑和文件名

os.path.splittext(file_url)返回的是文件地址和擴展名

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章