diff --git a/audeer/core/io.py b/audeer/core/io.py index b4a7efa..afdc4d2 100644 --- a/audeer/core/io.py +++ b/audeer/core/io.py @@ -970,6 +970,7 @@ def replace_file_extension( def rmdir( path: typing.Union[str, bytes], *paths: typing.Sequence[typing.Union[str, bytes]], + follow_symlink: bool = True, ): """Remove directory. @@ -982,9 +983,15 @@ def rmdir( *paths: additional arguments to be joined with ``path`` by :func:`os.path.join` + follow_symlink: if ``True`` + and path is a symbolic link, + the link and the folder it points to + will be removed Raises: NotADirectoryError: if path is not a directory + OSError: if ``follow_symlink`` is ``False`` + and ``path`` is a symbolic link Examples: >>> _ = mkdir("path1", "path2", "path3") @@ -995,7 +1002,7 @@ def rmdir( [] """ - path = safe_path(path, *paths) + path = safe_path(path, *paths, follow_symlink=follow_symlink) if os.path.exists(path): shutil.rmtree(path) diff --git a/tests/test_io.py b/tests/test_io.py index 8928329..8a677b1 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -1517,6 +1517,17 @@ def test_rmdir(tmpdir): audeer.rmdir("folder") assert not os.path.exists(path) os.chdir(current_path) + # Symbolic link + path = audeer.mkdir(tmpdir, "folder") + link = os.path.join(tmpdir, "link") + os.symlink(path, link) + with pytest.raises(OSError, match="symbolic link"): + audeer.rmdir(link, follow_symlink=False) + assert os.path.exists(link) + assert os.path.exists(path) + audeer.rmdir(link, follow_symlink=True) + assert not os.path.exists(link) + assert not os.path.exists(path) def test_touch(tmpdir):