Quantcast
Viewing latest article 12
Browse Latest Browse All 46

Answer by Marcel Wilson for How do I check whether a file exists without exceptions?

Adding one more slight variation which isn't exactly reflected in the other answers.

This will handle the case of the file_path being None or empty string.

def file_exists(file_path):    if not file_path:        return False    elif not os.path.isfile(file_path):        return False    else:        return True

Adding a variant based on suggestion from Shahbaz

def file_exists(file_path):    if not file_path:        return False    else:        return os.path.isfile(file_path)

Adding a variant based on suggestion from Peter Wood

def file_exists(file_path):    return file_path and os.path.isfile(file_path):

Viewing latest article 12
Browse Latest Browse All 46

Trending Articles