Home > Backend Development > Python Tutorial > How do I Delete Files and Folders in Python?

How do I Delete Files and Folders in Python?

DDD
Release: 2024-11-28 11:17:09
Original
131 people have browsed it

How do I Delete Files and Folders in Python?

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:

  • Path.unlink(): Removes a file or symbolic link.
  • Path.rmdir(): Removes an empty directory.

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:

  • os.remove(): Removes a file.
  • os.unlink(): Removes a symbolic link.
  • os.rmdir(): Removes an empty directory.

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()
Copy after login

To delete a directory named "my_directory" using shutil, you can use the following code:

import shutil

shutil.rmtree("my_directory")
Copy after login

To delete a symbolic link named "my_link" using os.unlink(), you can use the following code:

import os

os.unlink("my_link")
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template