Playback starts YouTube’s embedded player (privacy-enhanced mode).
Python Tutorial: How To Check if a File or Directory Exists
ChannelReal PythonDescription from the creator
dbader.org/python-tricks ► Master intermediate and advanced Python techniques with bitesized examples
A tutorial video on how to find out whether a file (or directory) exists using Python built-ins and functions from the standard library.
"How to Check if a File Exists in Python" (written tutorial) → dbader.org/blog/python-check-if-file-exists
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 #1: os.path.exists() and os.path.isfile()
The most common way to check for the existence of a file in Python is using the exists() and isfile() methods from the os.path module in the standard library.
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:"
Option #3: pathlib.Path.exists() (Python 3.4+)
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?
In most cases where you need a file existence check I’d recommend you use the built-in pathlib.Path.exists() method on Python 3.4 and above, or the os.path.exists() function on Python 2.
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.
Watch the full tutorial for details or check out dbader.org/blog/python-check-if-file-exists for a written tutorial covering the topics of this video.
FREE COURSE – "5 Thoughts on Mastering Python" dbader.org/python-mastery
SUBSCRIBE TO THIS CHANNEL: dbader.org/youtube
* * *
► Python Developer MUGS, T-SHIRTS & MORE: nerdlettering.com
FREE Python Coding Tutorials & News:
» Python Tutorials: dbader.org
» Python News on Twitter: twitter.com/@dbader_org
» Weekly Tips for Pythonistas: dbader.org/newsletter
» Subscribe to this channel: dbader.org/youtube
A tutorial video on how to find out whether a file (or directory) exists using Python built-ins and functions from the standard library.
"How to Check if a File Exists in Python" (written tutorial) → dbader.org/blog/python-check-if-file-exists
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 #1: os.path.exists() and os.path.isfile()
The most common way to check for the existence of a file in Python is using the exists() and isfile() methods from the os.path module in the standard library.
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:"
Option #3: pathlib.Path.exists() (Python 3.4+)
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?
In most cases where you need a file existence check I’d recommend you use the built-in pathlib.Path.exists() method on Python 3.4 and above, or the os.path.exists() function on Python 2.
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.
Watch the full tutorial for details or check out dbader.org/blog/python-check-if-file-exists for a written tutorial covering the topics of this video.
FREE COURSE – "5 Thoughts on Mastering Python" dbader.org/python-mastery
SUBSCRIBE TO THIS CHANNEL: dbader.org/youtube
* * *
► Python Developer MUGS, T-SHIRTS & MORE: nerdlettering.com
FREE Python Coding Tutorials & News:
» Python Tutorials: dbader.org
» Python News on Twitter: twitter.com/@dbader_org
» Weekly Tips for Pythonistas: dbader.org/newsletter
» Subscribe to this channel: dbader.org/youtube
About this tutorial
Real Python published this 17:00 video tutorial on October 25, 2017. It has been watched 51,227 times on YouTube.
- Channel
- Real Python
- Category
- Education
- Duration
- 17:00
- Published
- October 25, 2017
- Views
- 51,227
- Likes
- 451
Tags
Share
This tutorial in other languages
- FRPython Tutoriel: Comment vérifier si un fichier ou un répertoire Existent
- ESTutorial de Python: Cómo comprobar si un archivo o directorio existe
- PTPython Tutorial: Como verificar se um arquivo ou diretório existe
- ITPython Tutorial: Come controllare se un file o una directory
- DEPython Tutorial: Wie kann man überprüfen, ob eine Datei oder ein Verzeichnis existiert
- NLPython Tutorial: Hoe om te controleren of een bestand of map bestaat
- RUУчебник Python: Как проверить, если файл существует
- PLPython Tutorial: Jak sprawdzić, czy plik lub katalog istnieje
- JAPythonのチュートリアル:ファイルまたはディレクトリが存在する場合はどのようにチェックします
- ARبيثون البرنامج التعليمي: كيفية معرفة ما اذا كان ملف أو دليل موجود
- HIअजगर ट्यूटोरियल: कैसे की जाँच करने के लिए अगर एक फ़ाइल या निर्देशिका मौजूद है
- IDPython Tutorial: Cara Periksa apakah File atau Direktori Exists