Python check if dir exist

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
Читайте также:  Project management systems php

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 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.

Источник

In this article we will discuss techniques in python to check if a file exists or a link or a directory exists or not.

Python – Check if a path exists

Python’s os module provides a function to check if a given path exists or not i.e.

It will True if the path exists else it will give False. Parameter path can be a relative or an absolute path.
For example,

pathStr = '/home/varun/temp' # Check if path exists or not if os.path.exists(pathStr) : print("Path " , pathStr, " exists") else: print("Path " , pathStr, " does not exists")

Some Points to remember:

Frequently Asked:

  • In case path is of a symbolic link and link is broken i.e, file it points too doesn’t exists, then it will return False.
  • It can also return False if we don’t have permission to read the entity at given path.

With os.path.exists(path) we can make sure that given path exists or not but we can not make sure if it’s a file or directory or link.

Python – Check if a file exists

Python’s os module provides a function to check if a given file exists or not i.e.

It will return True if given path points to a file and that exists.

Why we need to check if a file exists ?

Suppose we want to open a file but if that file doesn’t exists then it will throw error FileNotFoundError at runtime i.e.

FileNotFoundError: [Errno 2] No such file or directory: ‘/home/varun/temp/sample1.csv’

To avoid this kind of error, we should first check if file exists or not. Let’s see how to do that i.e.

fileName = '/home/varun/temp/link.csv' # Check if given path exists and it is a file #if os.path.exists(fileName) and os.path.isfile(fileName): if os.path.isfile(fileName): # File exists, so now we can safely open the file fileHandler = open(fileName , "r") allData = fileHandler.read() fileHandler.close() print(allData) else: # File does not exist print("File Not Found")

Python – check if a Directory exists

Python’s os module provides a function to check if a given directory exists or not i.e.

It will return True if given path points to a directory and that exists.

dirName = '/home/varun/temp22' # Check if given path exists and it is a directory if os.path.isdir(dirName): print(dirName , ' exists and it is a Directory' ) else: # File does not exist print("Directory Not Found")

Both os.path.isdir() & os.path.isfile() returns True in case of symbolic links too (not broken). But we have another API to check separately if given path is a link or not.

On the similar lines, Python’s OS module provides a function to check if a given path is a link that exists i.e.

It will return True if given path points to a link, even if that is broken.

To check if given path is a link and that is not broken i.e. file/dir it points to exists, we need to use exists() along with islink() i.e.

linkPath = '/home/varun/temp/link.csv' # Check if given path is link if os.path.exists(linkPath) and os.path.islink(linkPath): print(linkPath , ' is a link and not broken' ) else: # File does not exist print("link Not Found or broken")

Complete example is as follows,

import os def main(): print("***** Check if a given path exists *****") pathStr = '/home/varun/temp' # Check if path exists or not if os.path.exists(pathStr) : print("Path " , pathStr, " exists") else: print("Path " , pathStr, " does not exists") print("***** Check if a file exists *****") fileName = '/home/varun/temp/link.csv' # Check if given path exists and it is a file #if os.path.exists(fileName) and os.path.isfile(fileName): if os.path.isfile(fileName): # File exists, so now we can safely open the file fileHandler = open(fileName , "r") allData = fileHandler.read() fileHandler.close() print(allData) else: # File does not exist print("File Not Found") print("***** Check if a Directory exists *****") dirName = '/home/varun/temp22' # Check if given path exists and it is a directory if os.path.isdir(dirName): print(dirName , ' exists and it is a Directory' ) else: # File does not exist print("Directory Not Found") print("***** Check if a link exists *****") linkPath = '/home/varun/temp/link.csv' # Check if given path is link if os.path.exists(linkPath) and os.path.islink(linkPath): print(linkPath , ' is a link and not broken' ) else: # File does not exist print("link Not Found or broken") if __name__ == '__main__': main()
***** Check if a given path exists ***** Path /home/varun/temp exists ***** Check if a file exists ***** Hello Hi ***** Check if a Directory exists ***** Directory Not Found ***** Check if a link exists ***** /home/varun/temp/link.csv is a link and not broken

Источник

Оцените статью