ManCity10
ManCity10

Reputation: 107

Selecting specific files in specific folders python os.walk

I have 20 subfolders in my Source folder. I want to do an os.walk on just 8 of those folders and select just the files with a txt extension. Is this possible?

import os
for root, dirs, files in os.walk(r'D:\Source'):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))

Upvotes: 0

Views: 5261

Answers (1)

Alexander Kosik
Alexander Kosik

Reputation: 669

You can use a positive list of directories like this:

import os
dirs_positive_list = ['dir_1', 'dir_2']

for root, dirs, files in os.walk(r'D:\Source'):
    dirs[:] = [d for d in dirs if d in dirs_positive_list]
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))

This will only process txt files which are present in dir_1 and dir_2

This in-place edit of rids is described in the help of os.walk

Or use a negative list, a so called 'black list':

import os
black_list = ['dir_3'] # insert your folders u do not want to process here

for root, dirs, files in os.walk(r'D:\Source'):
    print(dirs)
    dirs[:] = [d for d in dirs if d not in black_list]
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))

Upvotes: 2

Related Questions