Skip to content

Commit 4277aab

Browse files
committed
pathlib: Add missing_ok parameter to Path.unlink
Fixes bpo-33123
1 parent 9c463ec commit 4277aab

File tree

4 files changed

+23
-3
lines changed

4 files changed

+23
-3
lines changed

Doc/library/pathlib.rst

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1033,11 +1033,20 @@ call fails (for example because the path doesn't exist):
10331033
otherwise :exc:`FileExistsError` is raised.
10341034

10351035

1036-
.. method:: Path.unlink()
1036+
.. method:: Path.unlink(missing_ok=False)
10371037

10381038
Remove this file or symbolic link. If the path points to a directory,
10391039
use :func:`Path.rmdir` instead.
10401040

1041+
If *missing_ok* is false (the default), :exc:`FileNotFoundError` is
1042+
raised if the path does not exist.
1043+
1044+
If *missing_ok* is true, :exc:`FileNotFoundError` exceptions will be
1045+
ignored (same behavior as the POSIX ``rm -f`` command).
1046+
1047+
.. versionchanged:: 3.8
1048+
The *missing_ok* parameter was added.
1049+
10411050

10421051
.. method:: Path.write_bytes(data)
10431052

Lib/pathlib.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1256,14 +1256,18 @@ def lchmod(self, mode):
12561256
self._raise_closed()
12571257
self._accessor.lchmod(self, mode)
12581258

1259-
def unlink(self):
1259+
def unlink(self, missing_ok=False):
12601260
"""
12611261
Remove this file or link.
12621262
If the path is a directory, use rmdir() instead.
12631263
"""
12641264
if self._closed:
12651265
self._raise_closed()
1266-
self._accessor.unlink(self)
1266+
try:
1267+
self._accessor.unlink(self)
1268+
except FileNotFoundError:
1269+
if not missing_ok:
1270+
raise
12671271

12681272
def rmdir(self):
12691273
"""

Lib/test/test_pathlib.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1627,6 +1627,11 @@ def test_unlink(self):
16271627
self.assertFileNotFound(p.stat)
16281628
self.assertFileNotFound(p.unlink)
16291629

1630+
def test_unlink_missing_ok(self):
1631+
p = self.cls(BASE) / 'fileAAA'
1632+
self.assertFileNotFound(p.unlink)
1633+
p.unlink(missing_ok=True)
1634+
16301635
def test_rmdir(self):
16311636
p = self.cls(BASE) / 'dirA'
16321637
for q in p.iterdir():
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:class:`pathlib.Path.unlink` now accepts a +missing_ok* parameter to avoid a
2+
:exc:`FileNotFoundError` from being raised. Patch by Robert Buchholz.

0 commit comments

Comments
 (0)