0

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?

4

1 回答 1

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.
于 2013-05-11T05:58:51.643 回答