Answers for "python remove directory and all files"

38

python delete file

import os
import shutil

if os.path.exists("demofile.txt"):
  os.remove("demofile.txt") # one file at a time

os.rmdir("test_directory") # removes empty directory
shutil.rmtree("test_directory") # removes not empty directory and its content
Posted by: Guest on August-19-2020
5

python delete all files in directory

import os

filelist = [ f for f in os.listdir(mydir) if f.endswith(".bak") ]
for f in filelist:
    os.remove(os.path.join(mydir, f))
Posted by: Guest on June-05-2020
6

delete contents of directory python

import os
import glob

files = glob.glob('/YOUR/PATH/*')
for f in files:
    os.remove(f)
Posted by: Guest on November-20-2020
0

Python delete directory contents

import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
    file_path = os.path.join(folder, filename)
    try:
        if os.path.isfile(file_path) or os.path.islink(file_path):
            os.unlink(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)
    except Exception as e:
        print('Failed to delete %s. Reason: %s' % (file_path, e))
Posted by: Guest on September-06-2021

Code answers related to "python remove directory and all files"

Python Answers by Framework

Browse Popular Code Answers by Language