You can perform various directory related operation using os module in python. Let’s see some of the operation we can perform in directory.
Getting current directory
Knowing which workspace we are working on, is sometimes important. We can use getcwd() method on the os module to know the current working directory.
import os current_path = os.getcwd() print(current_path)
you will get the current working directory path
Creating a directory
You can use mkdir(pathtofile) method to create a directory. If the directory already exists it will throw error. Therefore we need to check if the directory exists or not and then create it. Let’s see an example
import os # create python_is_awesome directory os.mkdir('python_is_awesome')
It creates a directory name ‘python_is_awesome’.
You can check if the directory with this name is present or not with os.path.isdir(directory_path). Let’s see the an example
import os directory_name = 'python_is_awesome' if not os.path.isdir(directory_name): os.mkdir(directory_name)
You only create a directory if the directory is not present. Otherwise you skip creation.
Renaming a directory
You can rename a directory with os.rename(old_dir_path, new_dir_path). Let’s see an example
import os os.rename('python_is_awesome', 'python_is_everywhere')
If the directory is not present it will throw an error therefore like before we need to check if the directory with that name is available or not.
Removing a directory
You can use os.rmdir(dir_path) to remove a directory. Let’s see an example
import os os.rmdir('python_is_everywhere')
Listing file or directory in current working directory
You can use os.listdir(path=’.’) method to list directories or file. If no path is given it will return list of file and directories of current working directory.
import os print(os.listdir())
This is same as
import os print(os.listdir('.'))
The dot (‘.’) represents current working directory. Output: Gives list of directory in the current location.