Hi,

I started Python command prompt and entered this:

import distutils.dir_util as du

du.mkpath( "c:/foo/bar" ) #assume dir 'foo' doesn't exist

This works fine and it creates the path 'foo/bar'.

Now, go to file explorer and delete the dir 'foo' and go to the Python prompt and issue the same cmd.

du.mkpath( "c:/foo/bar" )
Now, it just returns []

OTOH, if you try
du.mkpath( "c:/foo/bar2" )
it craps with an exception:

Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
du.mkpath( "c:/foo/bar2")
File "C:\Python26\lib\distutils\dir_", line 80, in mkpath
"could not create '%s': %s" % (head, exc[-1])
DistutilsFileError: could not create 'c:\foo\bar2': The system cannot find the path specified


Same thing happens on Linux too.
Any help appreciated - as to my incorrect usage or anything else.
Thanks

Dani AI

Generated

For ’s example: this behavior is caused by an internal cache inside distutils.dir_util. mkpath records paths it has created in a module-level dictionary (_path_created) and will silently return an empty list on subsequent calls for the same absolute path — even if you removed the directories outside that Python process. This is an implementation detail (and the root of Bug 10948), not a filesystem bug. (android.googlesource.com)

Because of that cache, prefer APIs that don’t keep process-local state for general-purpose directory creation. As suggested, using the standard filesystem helpers avoids the surprising one-shot behavior; ’s pointer to higher-level file utilities is also sensible for broader tasks. For modern code a concise, robust option is pathlib:

from pathlib import Path
Path(r"C:\foo\bar").mkdir(parents=True, exist_ok=True)

This creates any missing parents and won’t error if the path already exists. (docs.python.org)

If you must keep using distutils for some reason, you can clear its cache in-process before calling mkpath again (or remove only the specific key). This is a workaround rather than a fix — it pokes an internal private variable:

import distutils.dir_util
distutils.dir_util._path_created.clear()

Clearing the cache has been suggested and used as a workaround in a number of reports. Use it only when you understand the risks of touching a private API. (stackoverflow.com)

Finally, note that distutils has been deprecated and removed from recent Python releases; favor os/pathlib/shutil APIs for new code. (peps.python.org)

Recommended Answers

All 2 Replies

what are you trying to do? A folder creation?

os.makedirs('c:\\foo\\bar')

Look here.
Cheers and Happy coding

I recommend Shutil module for file operations. You can even make class to deal with all basic file operations

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.