cinny
cinny

Reputation: 2412

Python - how do delete content in a complicated folder without changing its structure?

I have a folder with sub-folders, each can contain more sub-folders and so on. I want to delete all the files in all of them, but keeping the directory structure the same. Is there a built-in command or I have to write some recursive function for this using os.listdir?

Upvotes: 2

Views: 1115

Answers (3)

Mouna Cheikhna
Mouna Cheikhna

Reputation: 39678

import os

#check if file is hidden 
def is_hidden(filepath):
    name = os.path.basename(os.path.abspath(filepath))
    return name.startswith('.')

top = '/dir'
for root, dirs, files in os.walk(top):
    for name in files:
       #do not delete hidden files (as asked by OP in comments)
       if is_hidden(name) == false:  
          os.remove(os.path.join(root, name))

Upvotes: 1

johnsyweb
johnsyweb

Reputation: 141958

Shamelessly stolen from the Python Documentation on Files and Directories with the removal of directories omitted:

# 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))

Upvotes: 3

Francis Avila
Francis Avila

Reputation: 31641

See os.walk:

import os
top = '/some/dir'
for root, dirs, files in os.walk(top):
    for name in files:
        os.remove(os.path.join(root, name))

Upvotes: 1

Related Questions