Reputation: 4492
I have the following directory structure
top_folder
secondary_folder1
file1.txt
secondary_folder2
deep_folder
file2.txt
file3.txt
file4.html
file5.txt
file6.txt
I would like to access all the .txt
files that is in a folder within top_folder
(but not in any deeper folder). For example, here it is file1.txt
and file3.txt
. Is this possible using Python?
Upvotes: 0
Views: 2712
Reputation: 250881
You can use the glob
module:
import glob
import os
files = []
for x in os.listdir(path_to_top_folder):
if os.path.isdir(x):
for fil in glob.glob("{0}/*.txt".format(x)):
files += [os.path.split(fil)[-1]]
print files
or :
import glob
import os
files = [os.path.split(x)[-1] for x in glob.glob(path to tip_folder/*/*.txt)]
help on os.path.split
:
>>> os.path.split?
Definition: os.path.split(p)
Docstring:
Split a pathname. Returns tuple "(head, tail)" where "tail" is
everything after the final slash. Either part may be empty.
Upvotes: 1