I have a number of files in a folder. I want to delete each file once it has been processed.
What's the difference between using os.remove()
and os.unlink
? Which method is ideal for my scenario?
unlink() method in Python is used to remove or delete a file path. This method is semantically identical to os.
In Python, you can use the os. remove() method to remove files, and the os. rmdir() method to delete an empty folder. If you want to delete a folder with all of its files, you can use the shutil.
os. unlink() works for me. It removes the symlink without removing the directory that it links to.
They are identical as described in the official Python 2.7.15 documentation.
os.remove(path):
Remove (delete) the file path. If path is a directory, OSError is raised; see rmdir() below to remove a directory. This is identical to the unlink() function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.
Availability: Unix, Windows.
os.unlink(path):
Remove (delete) the file path. This is the same function as remove(); the unlink() name is its traditional Unix name.
Availability: Unix, Windows.
pathlib.Path
file access in Python v3.4 and higherWhile the question specifically asks for the os
module file removal, the latest versions of Python have another option for removing files that may be an alternative.
pathlib.Path.unlink()
pathlib.Path.remove()
does not existWhen using the pathlib module for file access, use pathlib.Path.unlink()
to remove files.
The Path.unlink()
method is a replacement for both os.remove()
and os.unlink()
. It is executed directly on a Path object, rather than being passed the location of a file through a string argument.
Starting in Python v3.4 the pathlib
builtin module is available to handle file access in an object-oriented manner. I believe a separate package is also available via Pip for older versions of Python.
With pathlib, you create folder and file objects that are of the Path
class. The related method of removing a file has been consolidated to just unlink()
. They do not have a remove()
method (likely because, per shash678's answer, there is no difference, it's just an alias). This appears to be equivalent to the os
methods of file deletion, other than the underlying means of specifying the file itself.
See Object Oriented file system paths, along with the table at the bottom that shows both os.remove()
and os.unlink()
map to Path.unlink()
.
In Python v3.8, a missing_ok argument was added to the Path.unlink()
function. When *missing_ok* == True
, an exception will not be raised if the file doesn't exist before trying to remove it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With