If you have a file, you can remove just that file with
If you have a (empty) directory, you can remove it with
If you have a path and want it and everything underneath it removed if possible, you can do so with
Also, older documentation stated that
Linux/Python 3.7.4
os.remove()
or os.unlink()
. Similar to /bin/rm
, this function fails on directories.If you have a (empty) directory, you can remove it with
os.rmdir()
. Similar to /bin/rmdir
.If you have a path and want it and everything underneath it removed if possible, you can do so with
shutil.rmtree()
. Similar to /bin/rm -r
.Also, older documentation stated that
os.remove()
would throw an OSError if it were handed a directory. Newer documentation states flatly that it now throws a IsADirectoryError. But it looks like that may be OS dependent. I do see the newer error on Linux, but I don't on MacOS (which still throws OSError, even on 3.8). I'm guessing that Windows does the same, but I can't test that immediately. Linux/Python 3.7.4
>>> os.remove("dir") Traceback (most recent call last): File "<stdin>", line 1, in <module> IsADirectoryError: [Errno 21] Is a directory: 'dir'MacOS/Python 3.8.2
>>> os.remove("dir") Traceback (most recent call last): File "<stdin>", line 1, in <module> PermissionError: [Errno 1] Operation not permitted: 'dir'