Python 3.4+pathlibfunction
.unlink()
operations
Delete a file or symlink; `missing_ok=True` suppresses FileNotFoundError. Use `.rmdir()` for directories.
Syntax
p.unlink(missing_ok=True)
The pattern if p.exists(): p.unlink() is a race — the file can vanish between the check and the delete, and you get FileNotFoundError anyway. Just call p.unlink(missing_ok=True) (added in Python 3.8) or catch the exception. On a symlink it removes the link itself and leaves the target file untouched; deletion is permanent and does not go through any trash.
Examples
from pathlib import Path
f = Path('hello_path.txt')
f.write_text('hi')
f.unlink() # → файл удалён
f.unlink(missing_ok=True) # → повторный вызов не падает
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy