How do I check whether a file exists without exceptions?

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

    Additionally, os.access():

    if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    

    Being R_OK, W_OK, and X_OK the flags to test for permissions (doc).

提交回复
热议问题