Python Directory
In this blog, we will learn about directory management in Python.
Directory class
A directory is a collection of files and sub-directories. Python provides os modules for dealing with directories.
Some important directory method they are listed below:
- getcwd()
- chdir()
- listdir()
- path.exists()
- mkdir()
- rename()
- rmdir()
Current Directory
getcwd() method is used to get your current working directory path.
- import os
- print(os.getcwd())
Change Directory
Change your current working directory using chdir() method. It takes a full file path.
- import os
- print(os.chdir('D:\\CCA'))
- print(os.getcwd())
List Directories and files
List all files and sub-directories inside a directory using listdir() method. The listdir() method take a full directory path. If you don't provide directory path then it takes the current working directory.
- import os
- print(os.listdir())
- print(os.listdir('D:\\CCA'))
Check if a directory exists or not
The path.exists() method is used to check if a directory exists or not. If directory exists than returns TRUE else returns FALSE.
- import os
- if os.path.exists('D:\\CCA\\Science'):
- print('Directory already exists.')
- else:
- print('Directory doesn\'t exists.')

Join the conversation! Your thoughts help the community grow.