In my code, I'm able to search through a directory for a file with a specific name. How could I edit the code so that it first searches for folders with names ending with the word "output". In the below code, when I tried to include the commented out line, the whole thing refused to run. Any help on what I'm missing would be greatly appreciated
def test():
file_paths = []
filenames = []
for root, dirs, files in os.walk('/Users/Bashe/Desktop/121210 p2/'):
for file in files:
#if re.match("output", file):
if re.match("Results",file):
file_paths.append(root)
filenames.append(file)
return file_paths, filenames
To search files that are in a folder with name ending with the word "output":
for dirpath, dirs, files in os.walk(rootdir):
if not dirpath.endswith('output'):
continue # look in the next folder
# search files
for file in files: ...
If you don't want even to visit any directories that are not ending with "output"
:
if not rootdir.endswith('output'):
return # do not visit it at all
for dirpath, dirs, files in os.walk(rootdir):
assert dirpath.endswith('output')
dirs[:] = [d for d in dirs if d.endswith('output')] # edit inplace
# search files
for file in files: ...
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.