Home >Backend Development >Python Tutorial >How to delete files and directories in python
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()