Filter your files with a list comprehension:
for dir, dirs, files in os.walk(src):
files = [os.path.join(dir, f) for f in files if not f.endswith('.txt')]
I removed the topdown=True
argument; it is the default.
Don't use glob.glob()
in combination with os.walk()
; both methods query the Operating System for the filenames in a directory. You already have those filenames at hand in the third value from each iteration over os.walk()
.
If you want to skip the whole directory, use the any()
function to see if there are any matching files, then use continue
ignore this directory:
for dir, dirs, files in os.walk(src):
if any(f.endswith('.txt') for f in files):
continue # ignore this directory
# do something with the files here, there are no .txt files.
files = [os.path.join(dir, f) for f in files]
If you want to ignore this directory and all its descendants, clear out the dirs
variable too using slice assignment:
for dir, dirs, files in os.walk(src):
if any(f.endswith('.txt') for f in files):
dirs[:] = [] # do not recurse into subdirectories
continue # ignore this directory
# do something with the files here, there are no .txt files.
files = [os.path.join(dir, f) for f in files]