python判断文件或文件夹是否存在

通过os.path.exists()方法判断。

例如:
判断E:\test文件夹是否存在,不存在则创建

import os
if os.path.exists('E:/test'):
    print('yes')
else:
    # os.mkdir('E:/test')
    os.makedirs('E:/test')
    print('success create dir test')

 

判断E:\test\1.txt文件是否存在,不存在则创建

if os.path.exists('E:/test/1.txt'):
    print('yes')
else:
     file = open('E:/test/1.txt', 'w')
     file.close
     print('success create file 1.txt')

 

posted @ 2020-08-04 12:55  轩辕吊雷  阅读(1305)  评论(0编辑  收藏  举报