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 directorydirName = '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.
Frequently Asked:
- Python: Add a column to an existing CSV file
- Python: Read CSV into a list of lists or tuples or dictionaries | Import csv to list
- Python: Get list of files in directory sorted by name
- Python: How to create a zip archive from multiple files or Directory
# Create target Directory if don't existif 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 existsos.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 existstry: 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 existsif not os.path.exists(dirName): os.makedirs(dirName) print("Directory " , dirName , " Created ")else: print("Directory " , dirName , " already exists")
Complete example is as follows,
import osdef 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 existsDirectory tempDir2/temp2/temp Created Directory tempDir2/temp2/temp already exists
Related posts:
- How to change current working directory in python ?
- Read a file line by line in Python (5 Ways)
- How to check if a file or directory or link exists in Python ?
- Python : How to move files and Directories ?
- Python : How to copy files from one location to another using shutil.copy()
- Python : How to remove files by matching pattern | wildcards | certain extensions only ?
- Python : How to remove a file if exists and handle errors | os.remove() | os.ulink()
- Python : How to delete a directory recursively using shutil.rmtree()
- Python: How to create a zip archive from multiple files or Directory
- Python : How to get the list of all files in a zip archive
- Python: How to unzip a file | Extract Single, multiple or all files from a ZIP archive
- How to append text or lines to a file in python?
- Python: How to delete specific lines in a file in a memory-efficient way?
- Python: Search strings in a file and get line numbers of lines containing the string
- Python: Get file size in KB, MB or GB – human-readable format
- Python: Three ways to check if a file is empty
- Python: Add a column to an existing CSV file