The mkdir you are using is this one in pathlib
(some of the comments were assuming os.mkdir
)
Path.mkdir(mode=0o777, parents=False, exist_ok=False)
Create a new
directory at this given path. If mode is given, it is combined with
the process’ umask value to determine the file mode and access flags.
If the path already exists, FileExistsError
is raised.
If parents is true, any missing parents of this path are created as
needed; they are created with the default permissions without taking
mode into account (mimicking the POSIX mkdir -p command).
If parents is false (the default), a missing parent raises
FileNotFoundError.
If exist_ok is false (the default), FileExistsError
is raised if the
target directory already exists.
If exist_ok is true, FileExistsError
exceptions will be ignored (same
behavior as the POSIX mkdir -p command), but only if the last path
component is not an existing non-directory file.
Changed in version 3.5: The exist_ok parameter was added.
It should work fine without parameters if you provide a valid path.
Note if you want to check if it exists, you'll need to call the exists()
method - don't forget the ()
However, it's not a great approach, because someone else could make the directory(or a file) at that path between when you check for it and when you get around to creating it. This is called a race condition.
It's better to wrap the mkdir
in a try/except
and let the OS tell you if there's a problem. There are a lot more possibilities for exceptions than just already existing. eg.
def directory():
p = Path(input("Enter file path: "))
try:
p.mkdir()
print('Directory does not exist. Making directory for you.')
except IOError as ex:
print('Couldn't create directory', ex)