How do I check whether a file exists without exceptions?

后端 未结 30 1946
北海茫月
北海茫月 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:16

    Check file or directory exists

    You can follow these three ways:

    Note1: The os.path.isfile used only for files

    import os.path
    os.path.isfile(filename) # True if file exists
    os.path.isfile(dirname) # False if directory exists
    

    Note2: The os.path.exists used for both files and directories

    import os.path
    os.path.exists(filename) # True if file exists
    os.path.exists(dirname) #True if directory exists
    

    The pathlib.Path method (included in Python 3+, installable with pip for Python 2)

    from pathlib import Path
    Path(filename).exists()
    

提交回复
热议问题