Deleting Files and Folders in Python
When working with files and folders in Python, it is often convenient to be able to delete them. Here are three common ways to do so:
1. Using pathlib
The pathlib module provides a cross-platform way to work with file paths. It offers the following two methods for deletion:
2. Using shutil
The shutil module provides a collection of utility functions for working with files and folders. It offers the rmtree() function for deleting a directory and all its contents recursively.
3. Using os
For Python versions 3.3 and below, you can use the following methods from the os module:
Usage Examples:
To delete a file named "myfile.txt" using pathlib, you can use the following code:
import pathlib path = pathlib.Path("myfile.txt") path.unlink()
To delete a directory named "my_directory" using shutil, you can use the following code:
import shutil shutil.rmtree("my_directory")
To delete a symbolic link named "my_link" using os.unlink(), you can use the following code:
import os os.unlink("my_link")
The above is the detailed content of How do I Delete Files and Folders in Python?. For more information, please follow other related articles on the PHP Chinese website!