In this article we will discuss different APIs in python to create directories.
Creating a Directory in Python
Python’s OS module provides a function to create a directory i.e.
os.mkdir(path)
It creates a directory with given path i.e.
os.mkdir('tempDir')
It creates the directory ‘tempDir’ in current directory.
If directory already exists then it will raise FileExistsError Error. So to avoid errors either we should call it using try / except i.e.
# Create directory dirName = 'tempDir' try: # Create target Directory os.mkdir(dirName) print("Directory " , dirName , " Created ") except FileExistsError: print("Directory " , dirName , " already exists")
or we should first check if given folder exists or not i.e.
# Create target Directory if don't exist if not os.path.exists(dirName): os.mkdir(dirName) print("Directory " , dirName , " Created ") else: print("Directory " , dirName , " already exists")
os.mkdir(path) will create the given directory only, but it will not create the intermediate directory in the given path.
For example we want to create ‘temp/tempDir2/sample’ in current working directory. But neither temp or tempDir2 is present in current working directory. Hence it will throw error i.e.
dirName = 'tempDir2/temp2/temp' os.mkdir(dirName)
Output:
FileNotFoundError: [Errno 2] No such file or directory: 'tempDir2/temp2/temp'
os.mkdir(path) can not create intermediate directories in the given path,if they are not present. It will throws error in such cases. For that we need another API.
Creating Intermediate Directories in Python
Python’s OS module provides an another function to create a directories i.e.
os.makedirs(path)
os.makedirs(name) will create the directory on given path, also if any intermediate-level directory don’t exists then it will create that too.
Its just like mkdir -p command in linux.
Let’s create a directory with intermediate directories i.e.
dirName = 'tempDir2/temp2/temp' # Create target directory & all intermediate directories if don't exists os.makedirs(dirName)
It will create all the directory ‘temp’ and all its parent directories if they don’t exists.
If target directory already exists then it will throw error. So, either call it using try / except i.e.
# Create target directory & all intermediate directories if don't exists try: os.makedirs(dirName) print("Directory " , dirName , " Created ") except FileExistsError: print("Directory " , dirName , " already exists")
or before calling check if target directory already exists i.e.
# Create target directory & all intermediate directories if don't exists if not os.path.exists(dirName): os.makedirs(dirName) print("Directory " , dirName , " Created ") else: print("Directory " , dirName , " already exists")
Complete example is as follows,
import os def main(): # Create directory dirName = 'tempDir' try: # Create target Directory os.mkdir(dirName) print("Directory " , dirName , " Created ") except FileExistsError: print("Directory " , dirName , " already exists") # Create target Directory if don't exist if not os.path.exists(dirName): os.mkdir(dirName) print("Directory " , dirName , " Created ") else: print("Directory " , dirName , " already exists") dirName = 'tempDir2/temp2/temp' # Create target directory & all intermediate directories if don't exists try: os.makedirs(dirName) print("Directory " , dirName , " Created ") except FileExistsError: print("Directory " , dirName , " already exists") # Create target directory & all intermediate directories if don't exists if not os.path.exists(dirName): os.makedirs(dirName) print("Directory " , dirName , " Created ") else: print("Directory " , dirName , " already exists") if __name__ == '__main__': main()
Output:
Directory tempDir Created Directory tempDir already exists Directory tempDir2/temp2/temp Created Directory tempDir2/temp2/temp already exists
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.