The answer is based on this where
- dirName: The next directory it found.
- subdirList: A list of sub-directories in the current directory.
- fileList: A list of files in the current directory.
Deletion cannot be done by list comprehension, because we have to "modify the subdirList in-place". Instead, we delete with enumerate
on a deep copy of the list so that the counter i
wouldn't be skipped after deletions while the original list gets modified.
I haven't tried it so don't trust this 100%.
# Import the os module, for the os.walk function
import os
# Set the directory you want to start from
rootDir = '.'
for dirName, subdirList, fileList in os.walk(rootDir):
print('Found directory: %s' % dirName)
for fname in fileList:
print('\t%s' % fname)
for i, elem in reversed(list(enumerate(subdirList[:]))):
if "[" in elem:
del subdirList[i]