23

I am writing boilerplate that handles command line arguments that will later be passed to another function. This other function will handle all of the directory creation (if necessary). Therefore my bp only needs to check if an input string could be a valid directory, OR a valid file, OR (some other thing). i.e. it needs to differentiate between something like "c:/users/username/" and "c:/users/username/img.jpg"

def check_names(infile):
    #this will not work, because infile might not exist yet
    import os
    if os.path.isdir(infile):
        <do stuff>
    elif os.path.isfile(infile):
        <do stuff>
    ...

The standard library does not appear to offer any solutions, but the ideal would be:

def check_names(infile):
    if os.path.has_valid_dir_syntax(infile):
        <do stuff>
    elif os.path.has_valid_file_syntax(infile):
        <do stuff>
    ...

After thinking about the question while typing it up, I can't fathom a way to check (only based on syntax) whether a string contains a file or directory other than the file extension and trailing slash (both of which may not be there). May have just answered my own question, but if anyone has thoughts about my ramblings please post. Thank you!

3 Answers 3

16

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))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, your observation is basically the "answer" although the answer I was looking for does not exist for that very reason. Directories can take crazy names on Windows as well, for example I just created a directory called ".../boat.jpg". The real question is how should the user specify a directory - that is essentially up to me to determine.
Thanks for your effort. But why extra os.path.dirname(path)), when you can use isdir() ?
@Jens dirname() strips off the last segment of the path, so /path/to/file becomes simply, /path/to
5

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 .

4 Comments

I don't think this will work. >>> os.path.isdir.__doc__ 'Return true if the pathname refers to an existing directory.'
@ChrisBarker Ah, yes, I missed the part where is could be a path. Thanks.
Thanks that post was helpful.
Unfortunately I can't upvote due to my newbie status, but consider this it.
2

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

2 Comments

@CrazyVideoGamez Invalid directory name would be in the realm of a try/catch block then. For example Path(r"C:\test?").exists() would produce OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\test?'. Or you could use regular expressions to check for invalid directory names.
since Python 3.12 supports / for Windows, and Unix, why did you add C:\ ? could be proofed with variable like /E/test - which is MinGW32/64-Bit style.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.