Home > Backend Development > Python Tutorial > How to delete files and directories in python

How to delete files and directories in python

高洛峰
Release: 2016-11-23 09:08:27
Original
1753 people have browsed it

Let’s take a look at how to delete a file and folder in python~~

First introduce the OS module

import os

Delete files:
os.remove()

Delete empty directories:
os.rmdir( )

Recursively delete empty directories:
os.removedirs()

Recursively delete directories and files (similar to the DOS command DeleteTree):
Method 1:

# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk( top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name) )

Method 2: Use python’s mature module
import shutil
shutil.rmtree()

Do it in one line__import__('shutil').rmtree()


Related labels:
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