how to delete a file or folder with python
• • ☕️ 1 min readhow to delete a file or folder with python
We’ll first try using the os module:
import os
open('example.txt','w').write('')
os.remove('example.txt')
it works with files.
let’s try it with an empty directory
let’s first create an empty directory:
os.mkdir('empty_dir')
os.remove('empty_dir')
It gives an error this time.
we’ll need another module for this task. we’ll use the shutil module.
import shutil
shutil.rmtree('empty_dir')
This time it works, and no error.
It even works with non-empty directories:
os.mkdir('non_empty')
open('non_empty/example.txt','w').write('')
shutil.rmtree('non_empty')
A video Tutorial: