Wednesday, December 25, 2024
Google search engine
HomeLanguagesCreate a directory in Python

Create a directory in Python

The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The os and os.path modules include many functions to interact with the file system. All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.

There are different methods available in the OS module for creating a director. These are –

Using os.mkdir()

os.mkdir() method in Python is used to create a directory named path with the specified numeric mode. This method raise FileExistsError if the directory to be created already exists.

Syntax: os.mkdir(path, mode = 0o777, *, dir_fd = None)

Parameter:
path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
mode (optional): A Integer value representing mode of the directory to be created. If this parameter is omitted then default value Oo777 is used.
dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.
If the specified path is absolute then dir_fd is ignored.

Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter.

Return Type: This method does not return any value.

Example #1: Use of os.mkdir() method to create directory/file




# Python program to explain os.mkdir() method
  
# importing os module
import os
  
# Directory
directory = "Lazyroar"
  
# Parent Directory path
parent_dir = "D:/Pycharm projects/"
  
# Path
path = os.path.join(parent_dir, directory)
  
# Create the directory
# 'GeeksForGeeks' in
# '/home / User / Documents'
os.mkdir(path)
print("Directory '% s' created" % directory)
  
# Directory
directory = "Geeks"
  
# Parent Directory path
parent_dir = "D:/Pycharm projects"
  
# mode
mode = 0o666
  
# Path
path = os.path.join(parent_dir, directory)
  
# Create the directory
# 'GeeksForGeeks' in
# '/home / User / Documents'
# with mode 0o666
os.mkdir(path, mode)
print("Directory '% s' created" % directory)


Output:

Directory 'Lazyroar' created
Directory 'Geeks' created

Example #2: Errors while using os.mkdir() method.




# Python program to explain os.mkdir() method  
      
# importing os module  
import os 
    
# Directory 
directory = "GeeksForGeeks"
    
# Parent Directory path 
parent_dir = "D:/Pycharm projects/"
    
# Path 
path = os.path.join(parent_dir, directory) 
    
# Create the directory 
# 'GeeksForGeeks' in 
# '/home / User / Documents' 
os.mkdir(path) 
print("Directory '% s' created" % directory) 
    
# if directory / file that  
# is to be created already 
# exists then 'FileExistsError' 
# will be raised by os.mkdir() method 
    
# Similarly, if the specified path 
# is invalid 'FileNotFoundError' Error 
# will be raised 


Output:

Traceback (most recent call last):
  File "gfg.py", line 18, in 
    os.mkdir(path)
FileExistsError: [WinError 183] Cannot create a file when that file /
                 /already exists: 'D:/Pycharm projects/GeeksForGeeks'

Example #3: Handling error while using os.mkdir() method.




# Python program to explain os.mkdir() method  
      
# importing os module  
import os 
    
# path 
path = 'D:/Pycharm projects / GeeksForGeeks'
    
# Create the directory 
# 'GeeksForGeeks' in 
# '/home / User / Documents' 
try
    os.mkdir(path) 
except OSError as error: 
    print(error)  


Output:

[WinError 183] Cannot create a file when that file/
              /already exists: 'D:/Pycharm projects/GeeksForGeeks'

Using os.makedirs()

os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.
For example, consider the following path:

D:/Pycharm projects/GeeksForGeeks/Authors/Nikhil

Suppose we want to create directory ‘Nikhil’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then os.makedirs() method will create all unavailable/missing directories in the specified path. ‘GeeksForGeeks’ and ‘Authors’ will be created first then ‘Nikhil’ directory will be created.

Syntax: os.makedirs(path, mode = 0o777, exist_ok = False)

Parameter:
path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
mode (optional): A Integer value representing mode of the newly created directory. If this parameter is omitted then the default value Oo777 is used.
exist_ok (optional): A default value False is used for this parameter. If the target directory already exists an OSError is raised if its value is False otherwise not.

Return Type: This method does not return any value.

Example #1: Use of os.makedirs() method to create directory.




# Python program to explain os.makedirs() method  
      
# importing os module  
import os 
    
# Leaf directory 
directory = "Nikhil"
    
# Parent Directories 
parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"
    
# Path 
path = os.path.join(parent_dir, directory) 
    
# Create the directory 
# 'Nikhil' 
os.makedirs(path) 
print("Directory '% s' created" % directory) 
    
# Directory 'GeeksForGeeks' and 'Authors' will 
# be created too  
# if it does not exists 
    
    
    
# Leaf directory 
directory = "c"
    
# Parent Directories 
parent_dir = "D:/Pycharm projects/Lazyroar/a/b"
    
# mode 
mode = 0o666
    
path = os.path.join(parent_dir, directory) 
    
# Create the directory 'c' 
     
os.makedirs(path, mode) 
print("Directory '% s' created" % directory) 
    
    
# 'GeeksForGeeks', 'a', and 'b' 
# will also be created if 
# it does not exists 
    
# If any of the intermediate level 
# directory is missing  
# os.makedirs() method will 
# create them 
    
# os.makedirs() method can be  
# used to create a directory tree  


Output:

Directory 'Nikhil' created
Directory 'c' created

Example #2:




# Python program to explain os.makedirs() method  
      
# importing os module  
import os 
    
# os.makedirs() method will raise 
# an OSError if the directory 
# to be created already exists 
    
       
# Directory 
directory = "Nikhil"
    
# Parent Directory path 
parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"
    
# Path 
path = os.path.join(parent_dir, directory) 
    
# Create the directory 
# 'Nikhil' 
os.makedirs(path) 
print("Directory '% s' created" % directory) 


Output:

Traceback (most recent call last):
  File "gfg.py", line 22, in 
    os.makedirs(path)
  File "C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python/
       / \Python38-32\lib\os.py", line 221, in makedirs
    mkdir(name, mode)
FileExistsError: [WinError 183] Cannot create a file when that/
               / file already exists: 'D:/Pycharm projects/GeeksForGeeks/Authors\\Nikhil'

Example #3: Handling errors while using os.makedirs() method.




# Python program to explain os.makedirs() method
  
# importing os module
import os
  
# os.makedirs() method will raise
# an OSError if the directory
# to be created already exists
# But It can be suppressed by
# setting the value of a parameter
# exist_ok as True
  
# Directory
directory = "Nikhil"
  
# Parent Directory path
parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"
  
# Path
path = os.path.join(parent_dir, directory)
  
# Create the directory
# 'Nikhil'
try:
    os.makedirs(path, exist_ok = True)
    print("Directory '%s' created successfully" % directory)
except OSError as error:
    print("Directory '%s' can not be created" % directory)
  
# By setting exist_ok as True
# error caused due already
# existing directory can be suppressed
# but other OSError may be raised
# due to other error like
# invalid path name


Output:

Directory 'Nikhil' created successfully

RELATED ARTICLES

Most Popular

Recent Comments