Python OS module, giving us the flexibility to access the directories, here we will see how to create or delete directories in python.
How to Create or Delete Directories in Python?
Getting the current working directory.
import os
print(os.getcwd())
Output:
D:\work\Python_repo
The os.getcwd() gives us the directory path, which we are working currently. As you can see in the output, currently I an in D:\work\Python_repo directory.
Now let’s create some directories in Python_repo.
Python create directory:
To create a directory in python os.mkdir()
method like below. It will create a directory on the current folder.
import os
os.mkdir("sample_dir")
print(os.listdir())
os.listdir()
prints the list of directories on the current working directory.
Output:
['sample_dir']
Python Create Sub Directories:
We can even create sub-directories within a directory using os.makedirs()
.
import os
os.makedirs("sample_dirs/sample-child")
It will create a sample-child directory under sample_dirs directory.
Python Delete Directory:
os.rmdir()
function allows us to remove a specific directory.
import os
os.rmdir("sample_dir")
print(os.listdir())
The above program will not print anything, as have deleted sample_dir directory in the current working directory.
Python Delete Sub Directories:
As we have created subdirectories in the above, we can also remove the sub-directories using os.removedirs()
function.
import os
os.removedirs("sample_dirs/sample-child")
The above program removes the specified directory path.
Happy Learning 🙂