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.')
Create a new directory
You can create a new directory using the mkdir() method. This method takes the full path of the new directory, if you don't provide a full path than the new directory is created in the current working directory.
- import os
- os.chdir('D:\\CCA')
- if os.path.exists('D:\\CCA\\Kumar'):
- print('Directory already exists.')
- else:
- os.mkdir('Kumar')
- print('Directory created successfully...')
Rename a directory
You can rename a directory using rename() method. This method takes two arguments. The first argument is old directory name and the second argument is new directory name.
- import os
- os.chdir('D:\\CCA')
- if os.path.exists('D:\\CCA\\Kumar'):
- os.rename('Kumar','Sarfaraj')
- print('Directory is renamed successfully...')
- else:
- print('Drectory doesn\'t exists.')
Delete a directory
The rmdir() method is used to delete an empty directory. It takes a full file path.
- import os
- os.chdir('D:\\CCA')
- if os.path.exists('D:\\CCA\\Sarfaraj'):
- os.rmdir('Sarfaraj')
- print('Directory deteted successfully...')
- else:
- print('Drectory doesn\'t exists.')
Summary
In this blog, I covered some directory related methods in python and saw examples of how to use these methods. Thanks for reading.