There are many functions in Python that delete files, but each has a different function.
directory
- A, OS. Unlink (path)
- Second, OS. Rmdir (path)
- Third, Shutil. Rmtree (path)
- Four, Send2trash (path)
There are many different ways to delete a file or folder in Python, but each has its own unique features and features.
In Python, you can delete files or folders using the following functions:
A, OS. Unlink (path)
path = ' D: \ DMP \ deposit \ Test TXT'
os.unlink(path)
Copy the code
This function is used to delete files in the OS module. It is used to delete files at path.
Note that this function only deletes files, permanently, and will not be found in the recycle bin. And it has no effect on folders! So when path points to a folder, it is not deleted.
Second, OS. Rmdir (path)
path = ' D: \ DMP \ deposit \ Test TXT'
os.rmdir(path)
Copy the code
This function relies on the OS module to permanently delete the folder at path. The feature of this function is that the folder to be deleted must be empty with no files or folders in it. And this function is complementary to the os.unlink() function.
This function can only delete empty folders, invalid for files specified in the path, and will report an error!
.
Third, Shutil. Rmtree (path)
path = ' D: \ DMP \ deposit \ Test TXT'
Shutil.rmtree(path)
Copy the code
To use this function, you must import the shutil module, which permanently deletes the folder at path, whether it is empty or not. If it is not empty, the files or folders contained in that folder are permanently deleted as well.
Note: the above three functions to delete files or folders are permanent delete, for improper procedures and accidentally delete files, is very dangerous.
Four, Send2trash (path)
path = ' D: \ DMP \ deposit \ Test TXT'
Send2trash.Send2trash(path)
Copy the code
Using this function requires importing the send2Trash module. Unlike the above three, the files it removes are relatively safe because it sends folders or files to the computer’s trash or recycle bin rather than permanently deleting them.
If you delete something you don’t want to because of a bug, you can find it in the computer’s recycle bin and restore it.
Therefore, it is recommended to use Send2trash(Path) to delete files or folders. It will temporarily store files in the recycle bin and can be recovered at any time, but the disadvantage is that it does not free disk space.
So if you delete files to reduce disk space, you can use the above three delete functions, but once deleted, there is no recovery!
Think useful remember to like attention yo!
You can also follow my wechat official account “Grey Wolf Hole Owner” for more useful Python technology sharing and Internet information!
Big bad Wolf is looking forward to progress with you!