Table of Contents
It is important to first check if the file or directory exists before trying to perform operations on it.
This is because you will get an error if the file or directory doesn't exist on the file system.
In this post, we'll learn about how to check if a file or directory exists using Python.
Checking if a file or directory exists
Thankfully, Python makes checking this easy for us.
Simply import the os
module which comes built-in to Python so we can have access to the os.path.exists()
function.
This function takes in a string representing the path of the file or directory you want to check.
The function will then return a bool
value representing whether or not the file or directory exists.
If it returns True
, then the file or directory exists, if not, then it will return False
.
Let's see how to use it:
PYTHONimport os
path = 'text.txt'
exists = os.path.exists(path)
print(exists)
BASHFalse
Remember that this function supports both files and directories.
Conclusion
In this post, we learned how to check if a file or directory exists in Python.
Simply use the os.path.exists()
function in the os
module to check a path.
Thanks for reading and happy coding!
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Creating a Twitter bot with Node.js
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript