我有以下目录结构
top_folder
secondary_folder1
file1.txt
secondary_folder2
deep_folder
file2.txt
file3.txt
file4.html
file5.txt
file6.txt
我想访问.txt
内文件夹中的所有top_folder
个文件(但不在任何更深的文件夹中)。例如,此处为file1.txt
和file3.txt
。这可能是使用Python吗?
答案 0 :(得分:1)
您可以使用glob
模块:
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
或:
import glob
import os
files = [os.path.split(x)[-1] for x in glob.glob(path to tip_folder/*/*.txt)]
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.