python检查文件是否存在,以及路径是否为文件,python路径,在写文件之前通常需要检查


在写文件之前通常需要检查文件路径是否可写:

from os import path, access, R_OK  # W_OK for write permission.PATH='./file.txt'if path.exists(PATH) and path.isfile(PATH) and access(PATH, R_OK):    print "File exists and is readable"else:    print "Either file is missing or is not readable"

你也可以通过下面的方式实现:

def file_exists(filename):    try:        with open(filename) as f:            return True    except IOError:        return False

评论关闭