mkdir and rmdir
- Python course
- Intermediate
- Lesson 79/116
- 5 min
Learn directory management with mkdir and rmdir.
Create a folder with mkdir
You create a folder with the p.mkdir() method. If the folder already exists, a FileExistsError is raised; to avoid this you can use p.mkdir(exist_ok=True). Then an existing folder is silently kept.
To create nested folders you use p.mkdir(parents=True); this also creates intermediate folders. For example Path("a/b/c").mkdir(parents=True) creates a, a/b and a/b/c in turn.
Practice Create a folder, check and remove
Start with from pathlib import Path. Create a path object with d = Path("new_folder"). Create the folder with d.mkdir(). Print whether it's a folder with print(d.is_dir()). Then remove it with d.rmdir() and print its existence with print(d.exists()).
Starter code
# Import the Path class
# Create the d path object, make the folder with mkdir
# Check with is_dir, remove with rmdir, print existsSample solution
# Import the Path class
from pathlib import Path
# Create the d path object, make the folder with mkdir
d = Path("new_folder")
d.mkdir()
# Check with is_dir, remove with rmdir, print exists
print(d.is_dir())
d.rmdir()
print(d.exists())Expected output
True False
Removing a folder with rmdir
You remove a folder with the p.rmdir() method. If the folder isn't empty, an OSError is raised; you must clear it first. This is a safety measure against accidental data loss.
To delete a folder with files inside you use shutil.rmtree(p); this removes it along with all its contents. rmdir is only for empty folders; this restriction is intentional design.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does mkdir() do on an existing folder?
- Moves to the parent
- Silently passes
- Empties the folder
- Raises FileExistsError Correct answer
Explanation: By default it errors; with exist_ok=True it passes silently.
2 Match the folder methods
| Term | Meaning |
|---|---|
mkdir |
Creates a folder |
rmdir |
Removes an empty folder |
exist_ok |
Passes if it exists |
parents |
Creates nested folders |
3 The parents parameter
p = Path("a/b/c")
p.mkdir(____=True)
p = Path("a/b/c")
p.mkdir(parents=True)
Explanation: parents=True creates nested folders.