Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shutil.rmtree to remove files only?

Tags:

python

I am using shutil.rmtree to remove a directory, but other processes (that I don't control) that create files in that tree are failing to create the files because the directories don't exist. Is there something as easy as shutil.rmtree that only deletes files but preserves directory structure?

like image 501
alejandro Avatar asked Jan 10 '14 20:01

alejandro


1 Answers

I don't think there's a built-in function to do this, but you could easily do it yourself using os.walk():

for dirpath, dirnames, filenames in os.walk(my_directory):
    # Remove regular files, ignore directories
    for filename in filenames:
        os.unlink(os.path.join(dirpath, filename))
like image 186
Adam Rosenfield Avatar answered Nov 10 '22 04:11

Adam Rosenfield