How do I check whether a file exists without exceptions?

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

    In 2016 the best way is still using os.path.isfile:

    >>> os.path.isfile('/path/to/some/file.txt')
    

    Or in Python 3 you can use pathlib:

    import pathlib
    path = pathlib.Path('/path/to/some/file.txt')
    if path.is_file():
        ...
    

提交回复
热议问题