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
?
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With