Python: How can I find all files with a particular extension?

前端 未结 13 1947
广开言路
广开言路 2020-12-13 14:05

I am trying to find all the .c files in a directory using Python.

I wrote this, but it is just returning me all files - not just .c files.

相关标签:
13条回答
  • 2020-12-13 14:47
    import os, re
    cfile = re.compile("^.*?\.c$")
    results = []
    
    for name in os.listdir(directory):
        if cfile.match(name):
            results.append(name)
    
    0 讨论(0)
  • 2020-12-13 14:49

    Just to be clear, if you wanted the dot character in your search term, you could've escaped it too:

    '.*[backslash].c' would give you what you needed, plus you would need to use something like:

    results.append(f), instead of what you had listed as results += [f]

    0 讨论(0)
  • 2020-12-13 14:50

    Try "glob":

    >>> import glob
    >>> glob.glob('./[0-9].*')
    ['./1.gif', './2.txt']
    >>> glob.glob('*.gif')
    ['1.gif', 'card.gif']
    >>> glob.glob('?.gif')
    ['1.gif']
    
    0 讨论(0)
  • 2020-12-13 14:56

    There is a better solution that directly using regular expressions, it is the standard library's module fnmatch for dealing with file name patterns. (See also glob module.)

    Write a helper function:

    import fnmatch
    import os
    
    def listdir(dirname, pattern="*"):
        return fnmatch.filter(os.listdir(dirname), pattern)
    

    and use it as follows:

    result = listdir("./sources", "*.c")
    
    0 讨论(0)
  • 2020-12-13 15:00

    KISS

    # KISS
    
    import os
    
    results = []
    
    for folder in gamefolders:
        for f in os.listdir(folder):
            if f.endswith('.c'):
                results.append(f)
    
    print results
    
    0 讨论(0)
  • 2020-12-13 15:01

    If you replace '.c' with '[.]c$', you're searching for files that contain .c as the last two characters of the name, rather than all files that contain a c, with at least one character before it.

    Edit: Alternatively, match f[-2:] with '.c', this MAY be computationally cheaper than pulling out a regexp match.

    0 讨论(0)
提交回复
热议问题