简体   繁体   中英

How to look for a specific file in first level directories in Python

I have a semi-complicated directory traversal that I need to perform. I have a program that I wrote that will require a SOURCE directory as a required parameter. I then need to get a list of FIRST LEVEL directories as I really only care about the first level. I then need to take that list of FIRST LEVEL directories and look to see if it contains a specific file. If it does, I want to add that first level directory to a list. So for I have done the following to get a list of the first level source. I am just unsure on how I would look under each of these directories to find the existence of a file. (something like *.proj). Any help you could provide would be awesome to point me in the right direction!

 for name in os.listdir(args.source):
        if os.path.isdir(args.source):
            self.tempSource.append(os.path.join(args.source, name))

You can use glob to search for files:

import glob
import os
files = []
for name in os.listdir(args.source):
    if os.path.isdir(name):
        files.append(glob.glob(os.path.join(args.source, name + "/*.proj"))) # match any files ending with .proj

The *.proj uses a wildcard, it will match any file ending with the extension .proj There is another short tutorial here :

You're checking whether the source directory is a directory repeatedly. You need to check the items inside that directory to see if they are directories. You also need to join the paths because listdir only returns names.

subpaths = (os.path.join(args.source, name) for name in os.listdir(args.source))
subdirs = list(filter(os.path.isdir, subpaths))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM