Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileExistsError in mkdir and makedirs in Python even if directory doesn't exist

I am trying to create two directories: foo1 and foo2.
There is nothing named foo1 in the current directory, but there is a file named foo2.

These are the results:

user@workstation:~/Desktop/newfolder$ ls
foo2
user@workstation:~/Desktop/newfolder$ file foo2
foo2: ASCII text
-----
>>> os.mkdir('foo1')
>>> os.mkdir('foo2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'foo2'
>>> os.makedirs('foo2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/janreggie/anaconda3/lib/python3.5/os.py", line 241, in makedirs
    mkdir(name, mode)
FileExistsError: [Errno 17] File exists: 'foo2'

Now, is there a way to create a directory foo2 while there is a file foo2?

like image 265
The Holy See Avatar asked Sep 13 '25 16:09

The Holy See


2 Answers

Wrap it in a try/except

def my_mkdir(dir):
    try:
        os.mkdir(dir)
    except:
        pass

Then use my_mkdir('foo1') and my_mkdir('foo2')

like image 193
piRSquared Avatar answered Sep 16 '25 06:09

piRSquared


Well, this is not a Python issue. This is an Operating System constraint. Are you working with Windows? As piRSquared stated before, you can't have two entities with same name in same directory. Once OS will make a difference between files and directories, it will allow Python to create a subdirectory with the same name than any already existing file. Furthermore, the 'try-except' proposal from piRSquared is a correct way to inform of issue while not stopping processing.

like image 21
Schmouk Avatar answered Sep 16 '25 04:09

Schmouk