Determine if string input could be a valid directory in Python

I don't know what OS you're using, but the problem with this is that, on Unix at least, you can have files with no extension. So ~/foo could be either a file or a directory.

I think the closest thing you could get is this:

def check_names(path):
    if not os.path.exists(os.path.dirname(path)):
        os.makedirs(os.path.dirname(path))

Unless I'm misunderstanding, os.path does have the tools you need.

def check_names(infile):
    if os.path.isdir(infile):
        <do stuff>
    elif os.path.exists(infile):
        <do stuff>
    ...

These functions take in the path as a string, which I believe is what you want. See os.path.isdir and os.path.exists.


Yes, I did misunderstand. Have a look at this post .


New since Python 3.4, you could also use pathlib module:

def check_names(infile):
    from pathlib import Path
    if Path(infile).exists():       # This determines if the string input is a valid path
        if Path(infile).is_dir():
            <do stuff>
        elif Path(infile).is_file():
            <do stuff>
    ...