filmov
tv
Python Tutorial: How To Check if a File or Directory Exists

Показать описание
A tutorial video on how to find out whether a file (or directory) exists using Python built-ins and functions from the standard library.
The ability to check whether a file exists on disk or not is important for many types of Python programs:
Maybe you want to make sure a data file is available before you try to load it, or maybe you want to prevent overwriting an existing file. The same is true for directories—maybe you need to ensure an output folder is available before your program runs.
In Python, there are several ways to verify a file or directory exists using functions built into the core language and the Python standard library.
In this tutorial you’ll see three different techniques for file existence checks in Python, with code examples and their individual pros and cons.
Option #2: open() and try...except
Another straightforward Python algorithm for checking whether a file exists: You simply attempt to open the file with the built-in open() function. Then you can look out for IOError exceptions like FileNotFoundError or PermissionError:
"FileNotFoundError: [Errno 2] No such file or directory: ..."
or
"PermissionError: Access is denied:"
Python 3.4 and above include the pathlib module that provides an object-oriented interface for dealing with file system paths. Using this module is much nicer than treating file paths as simple string objects.
What’s the preferred way to check if a file exists using Python?
However, there’s one important caveat to consider:
Keep in mind that just because a file existed when the check ran won’t guarantee that it will still be there when you’re ready to open it:
While unlikely under normal circumstances, it’s entirely possible for a file to exist in the instant the existence check runs, only to get deleted immediately afterwards.
To avoid this type of race condition, it helps to not only rely on a “Does this file exist?” check. Instead it’s usually better to simply attempt to carry out the desired operation right away. This is also called an “easier to ask for forgiveness than permission” (EAFP) style that’s usually recommended in Python.
* * *
FREE Python Coding Tutorials & News:
Комментарии