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))
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.