知识库
编程语言
Python
常用库

Libraries

Plot Libraries

matplotlib&seaborn

Math Libraries

Basic Libraries

  • python判断文件文件夹是否存在并创建

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