How do I check whether a file exists without exceptions?

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

    Use os.path.isfile() with os.access():

    import os
    
    PATH = './file.txt'
    if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
        print("File exists and is readable")
    else:
        print("Either the file is missing or not readable")
    

提交回复
热议问题