Search code examples
pythondarwinos.path

os.makedirs generates exception when a file exists with the same name in Python 2.7.10


Creating intermediate directories and leaf directory fails like the following example conditions (in MAC OS Darwin). There is a 'test' file in '/tmp' directory:

if os.path.isfile('/tmp/test'):
    if os.path.isdir('/tmp/test') is False:
        os.makedirs('/tmp/test')

Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-45-71969e2d9a17>", line 3, in <module>
os.makedirs('/tmp/test')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 17] File exists: '/tmp/test'

How can I create directories in this case?


Solution

  • As Simon Walker states this not a bug in Python or an implementation error. Operating systems (not only Darwin but other OSs like Windows) do not allow having a file and a directory with the same name in a directory. See an explanation for Unix/Linux.