How do I check whether a file exists without exceptions?

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

    You have the os.path.exists function:

    import os.path
    os.path.exists(file_path)
    

    This returns True for both files and directories but you can instead use

    os.path.isfile(file_path)
    

    to test if it's a file specifically. It follows symlinks.

提交回复
热议问题