在目录结构中访问带有通配符文件名的文件

时间:2013-05-11 05:54:52

标签: python file

我有以下目录结构

top_folder
  secondary_folder1
    file1.txt
  secondary_folder2
    deep_folder
      file2.txt
    file3.txt
    file4.html
  file5.txt
  file6.txt

我想访问.txt内文件夹中的所有top_folder个文件(但不在任何更深的文件夹中)。例如,此处为file1.txtfile3.txt。这可能是使用Python吗?

1 个答案:

答案 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.