Python 判断目录或文件是否存在

判断目录是否存在,若不存在,则创建

import os
dirs = '/Users/joseph/work/python/'

if not os.path.exists(dirs):
    os.makedirs(dirs)

判断文件是否存在,若不存在,则创建

import os
filename = '/Users/joseph/work/python/poem.txt'

if not os.path.exists(filename):
    os.system(r"touch {}".format(path))#调用系统命令行来创建文件

判断文件是否存在,若存在,则删除

# 写之前,先检验文件是否存在,存在就删掉
if os.path.exists("dest.txt"):
     os.remove("dest.txt")

 
原文地址:https://www.cnblogs.com/tonyxiao/p/14399115.html