Quantcast
Viewing latest article 21
Browse Latest Browse All 46

Answer by Zizouz212 for How do I check whether a file exists without exceptions?

Although I always recommend using try and except statements, here are a few possibilities for you (my personal favourite is using os.access):

  1. Try opening the file:

    Opening the file will always verify the existence of the file. You can make a function just like so:

    def File_Existence(filepath):    f = open(filepath)    return True

    If it's False, it will stop execution with an unhanded IOErroror OSError in later versions of Python. To catch the exception,you have to use a try except clause. Of course, you can alwaysuse a try except` statement like so (thanks to hsandtfor making me think):

    def File_Existence(filepath):    try:        f = open(filepath)    except IOError, OSError: # Note OSError is for later versions of Python        return False    return True
  2. Use os.path.exists(path):

    This will check the existence of what you specify. However, it checks for files and directories so beware about how you use it.

    import os.path>>> os.path.exists("this/is/a/directory")True>>> os.path.exists("this/is/a/file.txt")True>>> os.path.exists("not/a/directory")False
  3. Use os.access(path, mode):

    This will check whether you have access to the file. It will check for permissions. Based on the os.py documentation, typing in os.F_OK, it will check the existence of the path. However, using this will create a security hole, as someone can attack your file using the time between checking the permissions and opening the file. You should instead go directly to opening the file instead of checking its permissions. (EAFP vs LBYP). If you're not going to open the file afterwards, and only checking its existence, then you can use this.

    Anyway, here:

    >>> import os>>> os.access("/is/a/file.txt", os.F_OK)True

I should also mention that there are two ways that you will not be able to verify the existence of a file. Either the issue will be permission denied or no such file or directory. If you catch an IOError, set the IOError as e (like my first option), and then type in print(e.args) so that you can hopefully determine your issue. I hope it helps! :)


Viewing latest article 21
Browse Latest Browse All 46

Trending Articles