I would say that you can use glob.glob() to search for all the files you are looking for. The glob module finds all pathnames matching the given pattern according to the rules used by the Unix shell, although the results are returned in random order. From the documents -
glob.glob (path, *, recursive = False)
Return a possibly empty list of path names that match the path name, which should be a string containing the path. pathname can be either absolute (e.g. / usr / src / Python -1.5 / Makefile) or relative (e.g. .. / .. / Tools / * / *. gif) , and can contain shell-style wildcards. Broken symbolic links are included in the results (as in the shell).
Let's say our goal is to find all the text files from the directory, its subdirectories and the parent directory. Use os.walk() or os.chdir() to go to the directory you want to work with. So I went to my current working directory and from there I could access ALL text files with this piece of code -
import glob arr=glob.glob('*\*\*.txt') '''....thesis/tweets is the path I walked to which has further sub directories, tweets\LDA on tweets\test file for main reults , tweets\LDA on tweets\paris_tweet ,tweets\LDA on tweets\hurricane_patricia\ ''' count=0 for filename in arr: print (filename) count+=1 print("ran successfulyy!!!! count = ",count)
I get all text files (54) from all subdirectories. This conclusion shows a few -
LDA on tweets\paris_tweet\ldaparisresults.txt LDA on tweets\paris_tweet\ldaparisresults1.txt LDA on tweets\hurricane_patricia\80,xldahurricaneresults.txt LDA on tweets\hurricane_patricia\entitieshurricane.txt LDA on tweets\test file for main reults\80,10ldamainresults.txt LDA on tweets\test file for main reults\80,30ldamainresults.txt
To get text files from the parent directory (and its direct subdirectories), just change this to arr=glob.glob('..\*\*.txt')
source share