6

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

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
CG_corp
  • 103
  • 1
  • 1
  • 8

2 Answers2

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

Draconis
  • 3,209
  • 1
  • 19
  • 31
4

Have you read the docs for the os module?

Check out the following two links:

os.path.exists()

Return True if path refers to an existing path.

os.path.isdir()

Return True if path is an existing directory.

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65