How to remove all file from specific folder using python


Removing file through python is very easy, you need to import os library

and write code like this

Method 1 (os.remove())

import os
 
dir = 'path/to/dir'
for f in os.listdir(dir):
    os.remove(os.path.join(dir, f))

 

Method 2 (glob)

import os, glob
 
dir = 'path/to/dir'
filelist = glob.glob(os.path.join(dir, "*"))
for f in filelist:
    os.remove(f)

 

Method 3 (scandir)

import os, glob
 
dir = 'path/to/dir'
for file in os.scandir(dir):
    os.remove(file.path)
 

 

Method 4 (shutil.rmtree())

import os, shutil
 
dir = 'path/to/dir'
for files in os.listdir(dir):
    path = os.path.join(dir, files)
    try:
        shutil.rmtree(path)
    except OSError:
        os.remove(path)