How do I check whether a file exists without exceptions?

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

    import os
    #Your path here e.g. "C:\Program Files\text.txt"
    #For access purposes: "C:\\Program Files\\text.txt"
    if os.path.exists("C:\..."):   
        print "File found!"
    else:
        print "File not found!"
    

    Importing os makes it easier to navigate and perform standard actions with your operating system.

    For reference also see How to check whether a file exists using Python?

    If you need high-level operations, use shutil.

提交回复
热议问题