Question

I am attempting to write a quick piece of code that will check to see if a directory exists, if it does it will print that it does, if it does request permission to overwrite, and if not prompt to make the directory.

Here is what I have so far:

def mk_prjDir():
    print "Checking to see if", prjDir, "exists.."
    dirList = os.listdir(prjDir)
    for d in dirList:
        if os.path.isdir(d):
            print (prjDir, "exists!")
        else:
            print (prjDir, "does not exist!")

But every time I run it, if the directory isn't there it just dumps with an error. What am I doing wrong?

Update with traceback:

 Checking to see if /directory exists..
Traceback (most recent call last):
  File "alpha.py", line 73, in <module>
    mk_prjDir()
  File "alpha.py", line 50, in mk_prjDir
    dirList = os.listdir(prjDir)
OSError: [Errno 2] No such file or directory: '/directory'

Update #2: ospath was a typo, but the error remains.

I want to try and catch that exception. Should I be using a while == True: and a try/except? If so, what does that look like?

Was it helpful?

Solution

Firstly prjDir must be a full path to prjDir, i.e "\home\my_direc\", othwerise os.listdir will try to find prjDir in the current working directory of the script.

Secondly as os.listdir returns only file/directory names not the full path, so to get the full path you can use os.path.join(prjDir,d).

import os
def mk_prjDir():
    print "Checking to see if", prjDir, "exists.."
    dirList = os.listdir(prjDir)
    for d in dirList:
        if os.path.isdir(os.path.join(prjDir,d)):
            print (prjDir, "exists!")
        else:
            print (prjDir, "does not exist!")
mk_prjDir()

Update: I think I misunderstood your question if you only want to check whether a directory exists or not then try this:

def mk_prjDir():
    print "Checking to see if", prjDir, "exists.."
    if os.path.isdir(prjDir):
        print (prjDir, "exists!")
    else:
        print (prjDir, "does not exist!")

OTHER TIPS

os.listdir(dir) returns you a list of files found in the directory dir. As the error says, this directory does not exists, so, obviously, listdir can't list its contents.

Why are you doing this loop? Just use os.path.isdir to test if your directory exists.

Also see What is the naming convention in Python for variable and function names?

def mk_prjDir():
    print "Checking to see if", prjDir, "exists.."
    if os.path.isdir(prjDir):
        print (prjDir, "exists!")
    else:
        print (prjDir, "does not exist!")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top