- How to check if a file or directory exists in Python
- Use a try-except block¶
- Use os.path.isfile() , os.path.isdir() , or os.path.exists() ¶
- Use Path.is_file() from pathlib module¶
- Python – Check if Path is File or Directory
- Sample Code
- Examples
- 1. Check if the given path is a File
- 2. Check if given path is a Directory
- Summary
- Python: Check whether a file path is a file or a directory
- Python: Tips of the Day
- Python: Check if a File or Directory Exists
- Checking if a File Exists
- Checking if a Directory Exists
- Checking if Either Exist
- Advanced
- Free eBook: Git Essentials
How to check if a file or directory exists in Python
When you want to open a file and the corresponding file or directory of the given path does not exists, Python raises an Exception. You should address this, otherwise your code will crash.
This article presents different ways how to check if a file or a directory exists in Python, and how to open a file safely.
Use a try-except block¶
First of all, instead of checking if the file exists, it’s perfectly fine to directly open it and wrap everything in a try-except block. This strategy is also known as EAFP (Easier to ask for forgiveness than permission) and is a perfectly accepted Python coding style.
Note: In Python 2 this was an IOError.
Use os.path.isfile() , os.path.isdir() , or os.path.exists() ¶
If you don’t want to raise an Exception, or you don’t even need to open a file and just need to check if it exists, you have different options. The first way is using the different methods in os.path :
- os.path.isfile(path) : returns True if the path is a valid file
- os.path.isdir(path) : returns True if the path is a valid directory
- os.path.exists(path) : returns True if the path is a valid file or directory
Use Path.is_file() from pathlib module¶
Starting with Python 3.4, you can use the pathlib module. It offers an object-oriented approach to work with filesystem paths, and this is now my preferred way of dealing with files and directories.
You can create a Path object like this:
Now you can use the different methods is_file() , is_dir() , and exists() on the Path object:
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
PySaaS: The Pure Python SaaS Starter Kit
🚀 Build a software business faster with pure Python: Link*
* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏
Python – Check if Path is File or Directory
When you get a string value for a path, you can check if the path represents a file or a directory using Python programming.
To check if the path you have is a file or directory, import os module and use isfile() method to check if it is a file, and isdir() method to check if it is a directory.
In this tutorial, we shall learn how to check if a given path is file or folder, with the help of well detailed examples.
Sample Code
Following is a quick sample code snippet that demonstrates the usage of isfile() and isdir() functions.
import os #checks if path is a file isFile = os.path.isfile(fpath) #checks if path is a directory isDirectory = os.path.isdir(fpath)
Both the functions return a boolean value if the specified file path is a file or not; or directory or not.
Examples
1. Check if the given path is a File
In this example, consider that we have a file specified by the variable fpath. We will use isfile() method to check if we can find out if it is a file or not.
Python Program
import os fpath = 'D:/workspace/python/samplefile.txt' isFile = os.path.isfile(fpath) print('The file present at the path is a regular file:', isFile)
The file present at the path is a regular file: True
Now let us try with a path, that is a folder, passed as argument to isfile().
Python Program
import os fpath = 'D:/workspace/python/' isFile = os.path.isfile(fpath) print('The file present at the path is a regular file:', isFile)
The file present at the path is a regular file: False
That’s good. We are able to recognize if the specified path is a file or not.
2. Check if given path is a Directory
In the following example, consider that we have a folder or directory specified by the variable fpath. We will use isdir() method to check if we can find out if it is a file.
Python Program
import os fpath = 'D:/workspace/python/' isDirectory = os.path.isdir(fpath) print('Path points to a Directory:', isDirectory)
Path points to a Directory: True
Now let us try with a path, that is a file, passed as argument to isdir().
Python Program
import os fpath = 'D:/workspace/python/samplefile.txt' isDirectory = os.path.isdir(fpath) print('Path points to a Directory:', isDirectory)
Path points to a Directory: False
Again that’s good. It recognized if the path provided is a directory or not.
Summary
In this tutorial of Python Examples, we learned how to check if a given path is file or directory in Python, using isfile() and isdir(), with the help of well detailed examples.
Python: Check whether a file path is a file or a directory
Write a Python program to check whether a file path is a file or a directory.
Sample Solution:-
Python Code:
import os path="abc.txt" if os.path.isdir(path): print("\nIt is a directory") elif os.path.isfile(path): print("\nIt is a normal file") else: print("It is a special file (socket, FIFO, device file)" ) print()
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource’s quiz.
Follow us on Facebook and Twitter for latest update.
Python: Tips of the Day
How do I get a substring of a string in Python?
>>> x = "Hello World!" >>> x[2:] 'llo World!' >>> x[:2] 'He' >>> x[:-2] 'Hello Worl' >>> x[-2:] 'd!' >>> x[2:-2] 'llo Worl'
Python calls this concept «slicing» and it works on more than just strings. Take a look here for a comprehensive introduction.
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook
Python: Check if a File or Directory Exists
There are quite a few ways to solve a problem in programming, and this holds true especially in Python. Many times you’ll find that multiple built-in or standard modules serve essentially the same purpose, but with slightly varying functionality. Checking if a file or directory exists using Python is definitely one of those cases.
Here are a few ways to check for existing files/directories and their nuances. Throughout these examples we’ll assume our current working directory has these files and directories in it:
drwxr-xr-x 3 scott staff 102 Jan 12 10:01 dir -rw-r--r-- 1 scott staff 5 Jan 12 09:56 file.txt lrwxr-xr-x 1 scott staff 8 Jan 12 09:56 link.txt -> file.txt lrwxr-xr-x 1 scott staff 3 Jan 12 10:00 sym -> dir
Notice that we have one directory ( dir ), one file ( file.txt ), one file symlink ( link.txt ), and one directory symlink ( sym ).
Checking if a File Exists
This is arguably the easiest way to check if both a file exists and if it is a file.
import os os.path.isfile('./file.txt') # True os.path.isfile('./link.txt') # True os.path.isfile('./fake.txt') # False os.path.isfile('./dir') # False os.path.isfile('./sym') # False os.path.isfile('./foo') # False
Note that os.path.isfile does follow symlinks, so we get True when checking link.txt .
isfile is actually just a helper method that internally uses os.stat and stat.S_ISREG(mode) underneath, which we’ll touch on later.
Checking if a Directory Exists
Like the isfile method, os.path.isdir is the easiest way to check if a directory exists, or if the path given is a directory.
import os os.path.isdir('./file.txt') # False os.path.isdir('./link.txt') # False os.path.isdir('./fake.txt') # False os.path.isdir('./dir') # True os.path.isdir('./sym') # True os.path.isdir('./foo') # False
Again, just like isfile , os.path.isdir does follow symlinks. It is also just a simple wrapper around os.stat and stat.S_ISDIR(mode) , so you’re not getting much more than convenience from it.
Checking if Either Exist
Another way to check if a path exists (as long as you don’t care if the path points to a file or directory) is to use os.path.exists .
import os os.path.exists('./file.txt') # True os.path.exists('./link.txt') # True os.path.exists('./fake.txt') # False os.path.exists('./dir') # True os.path.exists('./sym') # True os.path.exists('./foo') # False
As you can see, it doesn’t care if the path points to a file, directory, or symlink, so it’s almost like you’re using isfile(path) or isdir(path) . But actually, internally it is just trying to call os.stat(path) , and if an error is thrown then it returns False .
Advanced
Throughout the article I’ve been mentioning how all of the above methods utilize the os.stat method, so I figured it would be useful to take a look at it. This is a lower-level method that will provide you with detailed information about files, directories, sockets, buffers, and more.
Like all the other methods we’v already covered, os.stat follows symlinks, so if you want to get the stat info on a link, try using os.lstat() instead.
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Since every operating system is different, the data provided by os.stat varies greatly. Here is just some of the data that each OS has in common:
- st_mode : protection bits
- st_uid : owner’s user id
- st_gid : owner’s group id
- st_size : size of file in bytes
- st_atime : time of last access
- st_mtime : time of last modification
- st_ctime : time of last metadata change on Unix, or time of creation on Windows
You can then use this data with the stat module to get interesting information, like whether a path points to a socket ( stat.S_ISSOCK(mode) ), or if a file is actually a named pipe ( stat.S_ISFIFO(mode) ).
If you need some more advanced functionality, then this is where you should go. But for 90% of the time you’re dealing with directories and files, the os or os.path modules should have you covered.
Although, one valid use-case might be when you’re doing multiple tests on the same file and want to avoid the overhead of the stat system call for each test. So if you have quite a few tests to do then this will help you do it more efficiently.