How do I check whether a file exists without exceptions?

后端 未结 30 1863
北海茫月
北海茫月 2020-11-21 05:07

How do I check if a file exists or not, without using the try statement?

30条回答
  •  余生分开走
    2020-11-21 05:41

    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):
    

提交回复
热议问题