python example Directory Create examples

This tutorials explains about Multiple ways to create an directory and nested directory in python with examples

Python How to create a simple Directory with example

  • use os makdir function
os.mkdir(path, mode=0o777, *, dir_fd=None)

Returns True or False

True - Creates an Directory if it does not exists False- Directory not created.

throws FileExistsError: Throws an error if Directory alread exists FileNotFoundError: This error throws if an parent directory does not exists

Python How to create a Nested Directory structure with example

  • use os makdirs function os library contains makedirs function, takes an path of an folder, creates an directory.
os.makedirs(name, mode=0o777, exist_ok=False

Here is an example

import os
nesteddirectory="c:\work\directory\test"
print(os.path.exists(nesteddirectory))
os.makedirs(nesteddirectory)

FileExistsError: [WinError 183] Cannot create a file when that file already exists: ‘c:\work\directory\directory’