Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Check if a directory exists using os module

I'm trying to validate if a directory received as user input exists using the os module

This is how I'm accepting the input:

directory = input("Hi ! \n please type a directory, thanks !")

The idea is that I want to make sure the user will type an existing directory and nothing else

like image 678
CG_corp Avatar asked Feb 27 '18 04:02

CG_corp


People also ask

How do you check if a directory exists or not in Python?

isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows a symbolic link, which means if the specified path is a symbolic link pointing to a directory then the method will return True.

How do you check if a file exists using os?

To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .


1 Answers

from pathlib import Path

def is_valid_directory(filename):
    p = Path(filename)
    return p.exists() and p.is_dir()

pathlib is an enormously convenient module for working with file paths of any sort. The p.exists() call is redundant since p.is_dir() returns False for nonexistent paths, but checking both would allow you to e.g. give better error messages.

EDIT: Note that pathlib was added in Python 3.4. If you're still using an old version for whatever reason, you can use the older os.path.isdir(filename) function.

like image 160
Draconis Avatar answered Sep 28 '22 17:09

Draconis