Path.mkdir
p.mkdir(parents=True, exist_ok=True) is the 'make sure this folder exists' idiom — it is os.makedirs(p, exist_ok=True). touch, unlink and rmdir cover the rest of the create/delete basics; for non-empty folders use shutil.rmtree.
Demo
from pathlib import Path p = Path('build/reports/2026') p.mkdir(parents=True, exist_ok=True) p.mkdir(parents=True, exist_ok=True) (p.is_dir(), sorted(q.as_posix() for q in Path('.').rglob('*')))
With parents=True every missing level is created, and exist_ok=True turns the second call into a no-op — so the idiom is safe to run on every start-up. Path('.') always exists, so mkdir(exist_ok=True) on it does nothing. The plain tab shows the error types only, because their messages differ by OS ([Errno 17] on Linux, [WinError 183] on Windows for the same FileExistsError).
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| parents | bool | no (False) | mkdir: also create missing parent folders (they get the default mode). |
| exist_ok | bool | no (False / True) | mkdir (default False): no error if the folder already exists. touch (default True): no error if the file exists — it just updates the modification time. |
| mode | int | no (0o777 / 0o666) | Permission bits, combined with the process umask (POSIX). |
| missing_ok | bool | no (False) | unlink (3.8+): no error if the file does not exist. |
Return value
None — All four act on the file system and return None.
Common patterns
from pathlib import Path out = Path('reports/2026/q3.csv') out.parent.mkdir(parents=True, exist_ok=True) out.write_text(csv_text, encoding='utf-8')
from pathlib import Path Path('app.pid').unlink(missing_ok=True)
import shutil from pathlib import Path shutil.rmtree(Path('build'), ignore_errors=True)
from pathlib import Path try: Path('setup.done').touch(exist_ok=False) except FileExistsError: print('already set up')
Examples
Pitfalls
from pathlib import Path Path('out').mkdir() try: Path('out').mkdir() except OSError as e: result = type(e).__name__ result
from pathlib import Path Path('out').mkdir() Path('out').mkdir(exist_ok=True) Path('out').is_dir()
from pathlib import Path Path('data').touch() try: Path('data').mkdir(exist_ok=True) except OSError as e: result = type(e).__name__ result
from pathlib import Path Path('data').touch() p = Path('data') 'use another name' if p.exists() and not p.is_dir() else p.mkdir(exist_ok=True)
from pathlib import Path p = Path('tmp.lock') if p.exists(): p.unlink() p.exists()
from pathlib import Path p = Path('tmp.lock') p.unlink(missing_ok=True) p.exists()
When to use
- Making output folders (mkdir(parents=True, exist_ok=True))
- Creating empty marker files (touch) and removing files (unlink)
- Removing folders you have emptied (rmdir)
- Deleting a folder with content → shutil.rmtree
- Temporary folders → tempfile.TemporaryDirectory
Notes
FAQ
Path('folder').mkdir(parents=True, exist_ok=True). parents creates missing parent folders, exist_ok skips the error if it is already there.