Reputation: 2412
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
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
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
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