python判斷目錄是否存在,不存在創(chuàng)建一個(gè)新的:
importos
ifnotos.path.isdir(dir_name):
os.makedirs(dir_name)
os.mkdir()創(chuàng)建路徑中的最后一級(jí)目錄,而如果之前的目錄不存在并且也需要?jiǎng)?chuàng)建的話,就會(huì)報(bào)錯(cuò)。
os.makedirs()創(chuàng)建多層目錄,如果中間目錄都不存在的話,會(huì)自動(dòng)創(chuàng)建。
判斷文件是否存在
importos
filename='/Users/joseph/work/python/poem.txt'
ifnotos.path.exists(filename):
os.system(r"touch{}".format(path))#調(diào)用系統(tǒng)命令行來創(chuàng)建文件
以上內(nèi)容為大家介紹了python培訓(xùn)之目錄不存在則創(chuàng)建,希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。