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

How to delete files and directories in python

高洛峰
高洛峰Original
2016-11-23 09:08:271757browse

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()


Statement:
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