os.mkdir(path) returns OSError when directory does not exist

PythonSystemMkdir

Python Problem Overview


I am calling os.mkdir to create a folder with a certain set of generated data. However, even though the path I specified has not been created, the os.mkdir(path) raises an OSError that the path already exists.

For example, I call:

os.mkdir(test)

This call results in OSError: [Errno 17] File exists: 'test' even though I don't have a test directory or a file named test anywhere.

NOTE: the actual path name I use is not "test" but something more obscure that I'm sure is not named anywhere.

Help, please?

Python Solutions


Solution 1 - Python

Greg's answer is correct but doesn't go far enough. OSError has sub-error conditions, and you don't want to suppress them all every time. It's prudent to trap just expected OS errors.

Do additional checking before you decide to suppress the exception, like this:

import errno
import os

try:
    os.mkdir(dirname)
except OSError as exc:
    if exc.errno != errno.EEXIST:
        raise
    pass

You probably don't want to suppress errno.EACCES (Permission denied), errno.ENOSPC (No space left on device), errno.EROFS (Read-only file system) etc. Or maybe you do want to -- but that needs to be a conscious decision based on the specific logic of what you're building.

Greg's code suppresses all OS errors; that's unsafe just like except Exception is unsafe.

As others have pointed out, newer versions of Python provide os.makedirs() that attempts to create the dir only if it doesn't exist, equivalent to mkdir -p from a unix command line.

Solution 2 - Python

In Python 3.2 and above, you can use:

os.makedirs(path, exist_ok=True)

to avoid getting an exception if the directory already exists. This will still raise an exception if path exists and is not a directory.

Solution 3 - Python

Just check if the path exist. if not create it

import os    
if not os.path.exists(test):
    os.makedirs(test)

Solution 4 - Python

Happened to me on Windows, maybe this is the case:

Like you I was trying to :

os.mkdir(dirname)

and got OSError: [Errno 17] File exists: '<dirname>'. When I ran:

os.path.exists(dirname)

I got false, and it drove me mad for a while :)

The problem was: In a certain window I was at the specific directory. Even though it did not exists at that time (I removed it from linux). The solution was to close that window \ navigate to somewhere else. Shameful, I know ...

Solution 5 - Python

I also faced the same problem, specially, when the string 'test' contains the multiple directory name. So when 'test' contains the single directory -

if not os.path.exists(test):
    try:
	    os.makedir(test)
    except:
	    raise OSError("Can't create destination directory (%s)!" % (test))  

If the 'test' contains multiple directory like '\dir1\dir2' then -

if not os.path.exists(test):
    try:
	    os.makedirs(test)
    except:
	    raise OSError("Can't create destination directory (%s)!" % (test))  

Solution 6 - Python

You have a file there with the name test. You can't make a directory with that exact same name.

Solution 7 - Python

Simple answer that does not require any additional import, does not suppress errors such as "permission denied", "no space left on device" etc., yet accepts that the directory may already exist:

import os

try:
    os.mkdir(dirname)
except FileExistsError :
    pass
except :
    raise

Solution 8 - Python

I don't know the specifics of your file system. But if you really want to get around this maybe use a try/except clause?

try:
    os.mkdir(test)
except OSError:
    print "test already exists"

You can always do some kind of debugging in the meanwhile.

Solution 9 - Python

Maybe there's a hidden folder named test in that directory. Manually check if it exists.

ls -a

Create the file only if it doesn't exist.

if not os.path.exists(test):
    os.makedirs(test)

Solution 10 - Python

For python 2.7

from distutils.dir_util import mkpath
mkpath(path)

Solution 11 - Python

Didn't see any other answers or comments about this particular solution. But make sure if you are actively managing folder permissions that you sign out and sign back in before running your code. I banged my head against the wall for about an hour trying to figure out what my issue was, and this was it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionQuanquan LiuView Question on Stackoverflow
Solution 1 - PythonChris JohnsonView Answer on Stackoverflow
Solution 2 - Python1''View Answer on Stackoverflow
Solution 3 - PythonlordkainView Answer on Stackoverflow
Solution 4 - PythonOmer DaganView Answer on Stackoverflow
Solution 5 - PythonAnupam BeraView Answer on Stackoverflow
Solution 6 - PythonCT ZhuView Answer on Stackoverflow
Solution 7 - PythonGeorgView Answer on Stackoverflow
Solution 8 - PythonGregView Answer on Stackoverflow
Solution 9 - PythonTabraiz AliView Answer on Stackoverflow
Solution 10 - PythonAhsan aslamView Answer on Stackoverflow
Solution 11 - PythonJeremy WView Answer on Stackoverflow