How do I check whether a file exists without exceptions?

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

    This is the simplest way to check if a file exists. Just because the file existed when you checked doesn't guarantee that it will be there when you need to open it.

    import os
    fname = "foo.txt"
    if os.path.isfile(fname):
        print("file does exist at this time")
    else:
        print("no such file exists at this time")
    

提交回复
热议问题