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则不需要
    '''

 

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