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

前端 未结 13 2004
广开言路
广开言路 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:45

    For another alternative you could use fnmatch

    import fnmatch
    import os
    
    results = []
    for root, dirs, files in os.walk(path)
        for _file in files:
            if fnmatch.fnmatch(_file, '*.c'):
                results.append(os.path.join(root, _file))
    
    print results
    

    or with a list comprehension:

    for root, dirs, files in os.walk(path)
        [results.append(os.path.join(root, _file))\
            for _file in files if \
                fnmatch.fnmatch(_file, '*.c')] 
    

    or using filter:

    for root, dirs, files in os.walk(path):
        [results.append(os.path.join(root, _file))\
            for _file in fnmatch.filter(files, '*.c')]     
    

提交回复
热议问题