How to delete files and directories in python
Nov 23, 2016 am 09:08 AMLet’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()

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the advantages and disadvantages of templating?

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers

For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step

Share several .NET open source AI and LLM related project frameworks

A complete guide to golang function debugging and analysis
