Reputation: 67
I have a list of strings (stored in a .txt file, one string per line) and I want to make a script that takes the first line and search all folders names in a directory, and the takes the second line and search all folders names and so on. How do I do this? Hope i made my self clear. Thks!
Upvotes: 0
Views: 801
Reputation: 6053
Assuming that by searching all folders you mean printing them out to the standard output you can do this:
from os import listdir
from os.path import isdir, join
with open('directories.txt', 'r') as f:
i = 1
for line in f.readlines():
directories = []
tmp = line.strip('\n')
for d in listdir(tmp):
if isdir(join(tmp, d)):
directories.append(d)
print('directory {}: {}'.format(i, directories))
i += 1
It will output something like this:
directory 1: ['subfolder_1', 'subfolder_0']
directory 2: ['subfolder_0']
directory 3: []
Note that I recommend using with
in order to open files since it will automatically properly close them even if exceptions occur.
Upvotes: 1
Reputation: 41
This example reads paths from text file and prints them out. Replace the print with your search logic.
import os
textfile = open('C:\\folder\\test.txt', 'r')
for line in textfile:
rootdir = line.strip()
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print(os.path.join(subdir, file))
Upvotes: 1