How do I check whether a file exists without exceptions?

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

    You can write Brian's suggestion without the try:.

    from contextlib import suppress
    
    with suppress(IOError), open('filename'):
        process()
    

    suppress is part of Python 3.4. In older releases you can quickly write your own suppress:

    from contextlib import contextmanager
    
    @contextmanager
    def suppress(*exceptions):
        try:
            yield
        except exceptions:
            pass
    

提交回复
热议问题