2

I'm trying to create a folder, handling the different errors (FileExistsError if the folder already exists and OSError if the folder's name contains illegal characters), but Python seems to always choose the first except block when catching an error no matter which one it is and the order they are.

Is there anything I didn't understand?

import os
from pathlib import Path

def generateSetup(name) :
    dir_path = os.path.dirname(os.path.realpath(__file__))
    if not Path(dir_path + '/setups').exists() : os.mkdir(dir_path + '/setups')

    try : os.mkdir(dir_path + '/setups/' + name)
    except FileExistsError : print('The file already exists')
    except OSError : print('The name contains illegal characters')

stp_name = input('Enter your setup\'s name :')
generateSetup(stp_name)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
KanarchiK
  • 33
  • 3
  • 2
    Please use proper Python style when writing code. Although it is syntactically permitted to put the body of a block on the same line as the introducing statement, it is unnecessarily hard to read and not recommended. – Daniel Roseman Jul 17 '18 at 11:21

2 Answers2

2

There is nothing wrong with your code. It works properly as intended, catches FileExistsError if the directory already exists or OSError if the directory name contains invalid symbols. So I assume the problem is in the way you are testing the code

>>> dloc='tmp/\/b'
>>> try:
...     os.mkdir(dloc)
... except FileExistsError:
...     print('The file already exists')
... except OSError:
...     print('The name contains illegal characters')
... 
The name contains illegal characters
Sunitha
  • 11,777
  • 2
  • 20
  • 23
  • You're right, this is the way I am testing the code. I just discovered that "\\\\" as a folder name raises a FileExistsError, though I don't know why. – KanarchiK Jul 17 '18 at 11:56
  • I assume you are using windows. On windows, `"\\\\"` is a valid directory name and just means `'\'`. – Sunitha Jul 17 '18 at 12:25
0

we can give any name to directory there is no naming conventions to follow for creating directory through python code. In this case only the first except block will throw the message if entered name is already a directory name otherwise not.