How to use glob() output as input to os.listdir() I'm trying to use the output of glob.glob() as the input to os.listdir() in order to get the number of files in the directory. The output of glob() gives the following:

f = glob.glob(ct)
print(f)

['C:\\Users\\tennant\\Desktop\\RF WAVEFORMS\\SPRING 2018\\RF\\1L22\\2018_05_02\\133258.2']


which, if I try to use as input to listdir() gives the following error

test = os.listdir(str(f))




Eventually through enough trial and error, I was able to find a solution.

f = glob.glob(ct)
fnew = str(f).strip('[]')
test = os.listdir(fnew.replace('\'',""))
print(fnew.replace('\'',""), len(test))

C:\\Users\\tennant\\Desktop\\RF WAVEFORMS\\SPRING 2018\\RF\\1L22\\2018_05_02\\133258.2 7



However it's messy and I'm clearly not understanding something more fundamental about the output of glob() or strings in general. Anything that could clean this code up and help my understanding would be greatly appreciated!
Assuming you have a string to pass into glob that does wildcard matching, glob will return a list of matches. So you don't need to make a string out of that list and replace the square-brackets and so on. You can just iterate over that list and do something with each of the values, which are already strings.

results = glob.glob(your_pattern)


Based on your code, the results is actually a list of folder names for which you want to count the number of files in each. We can loop over results and print the counts:

for folder in results:
    n = len(os.listdir(folder))
    print("Folder: {0} --&gt; \t {1} files".format(folder, n))