In this post, you’ll learn about file and directory management in Python, i.e. creating a directory, renaming it, listing all directories and working with them.
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() method is used to get your current working directory path.
import os
print(os.getcwd())
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 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'))
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.')
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') #Change the current path
if os.path.exists('D:\\CCA\\Kumar'): #Check directory exists or not
print('Directory already exists.')
else:
os.mkdir('Kumar') #directory creating
print('Directory created successfully...')
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.')
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.')
In this post, I covered some directory related methods in python and saw examples of how to use these methods. Thanks for reading.
#python #Directory # Files Management