python判斷文件文件夾是否存在並創建

方式還是有挺多的,這裏採取最爲簡單的os包

import os
import codecs

# 判斷文件夾是否存在,不存在則創建
dirs1 = 'D:\\history' 
if not os.path.exists(dirs1):
    os.makedirs(dirs1)

# 判斷文件是否存在,不存在則創建
file1 = 'D:\\conf.ini'
if not os.path.exists(file1):
    # w是覆蓋,a是追加,a+,w+是如不存在就創建
    with codecs.open(file1,'a+',encoding='utf-8') as f:
        f.write("")    

    '''
    這裏多說一句
    使用codecs的with open的好處是,平常的open需要打開之後需要close
    因爲open之後是放在內存裏寫的,關閉之後數據纔會寫到硬盤裏,否則會造成部分數據丟失
    而with則不需要
    '''

 

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