Skip to content

bpo-33123: pathlib: Add missing_ok parameter to Path.unlink #6191

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion Doc/library/pathlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1033,11 +1033,20 @@ call fails (for example because the path doesn't exist):
otherwise :exc:`FileExistsError` is raised.


.. method:: Path.unlink()
.. method:: Path.unlink(missing_ok=False)

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

If *missing_ok* is false (the default), :exc:`FileNotFoundError` is
raised if the path does not exist.

If *missing_ok* is true, :exc:`FileNotFoundError` exceptions will be
ignored (same behavior as the POSIX ``rm -f`` command).

.. versionchanged:: 3.8
The *missing_ok* parameter was added.


.. method:: Path.write_bytes(data)

Expand Down
8 changes: 6 additions & 2 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1256,14 +1256,18 @@ def lchmod(self, mode):
self._raise_closed()
self._accessor.lchmod(self, mode)

def unlink(self):
def unlink(self, missing_ok=False):
"""
Remove this file or link.
If the path is a directory, use rmdir() instead.
"""
if self._closed:
self._raise_closed()
self._accessor.unlink(self)
try:
self._accessor.unlink(self)
except FileNotFoundError:
if not missing_ok:
raise

def rmdir(self):
"""
Expand Down
5 changes: 5 additions & 0 deletions Lib/test/test_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1627,6 +1627,11 @@ def test_unlink(self):
self.assertFileNotFound(p.stat)
self.assertFileNotFound(p.unlink)

def test_unlink_missing_ok(self):
p = self.cls(BASE) / 'fileAAA'
self.assertFileNotFound(p.unlink)
p.unlink(missing_ok=True)

def test_rmdir(self):
p = self.cls(BASE) / 'dirA'
for q in p.iterdir():
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
:class:`pathlib.Path.unlink` now accepts a *missing_ok* parameter to avoid a
:exc:`FileNotFoundError` from being raised. Patch by Robert Buchholz.