Python:如何查找具有特定扩展名的所有文件?

时间:2010-08-31 11:13:15

标签: python

我正在尝试使用Python查找目录中的所有.c文件。

我写了这个,但它只是将所有文件归还给我 - 而不仅仅是.c个文件。

import os
import re

results = []

for folder in gamefolders:
    for f in os.listdir(folder):
        if re.search('.c', f):
            results += [f]

print results

如何获取.c个文件?

14 个答案:

答案 0 :(得分:33)

尝试将内部循环更改为类似

的内容
results += [each for each in os.listdir(folder) if each.endswith('.c')]

答案 1 :(得分:26)

尝试“glob”:

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']

答案 2 :(得分:4)

for _,_,filenames in os.walk(folder):
    for file in filenames:
        fileExt=os.path.splitext(file)[-1]
        if fileExt == '.c':
            results.append(file)

答案 3 :(得分:4)

KISS

# KISS

import os

results = []

for folder in gamefolders:
    for f in os.listdir(folder):
        if f.endswith('.c'):
            results.append(f)

print results

答案 4 :(得分:2)

对于另一种选择,您可以使用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

或列表理解:

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

或使用过滤器:

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

答案 5 :(得分:2)

有一个更好的解决方案,直接使用正则表达式,它是标准库的模块fnmatch来处理文件名模式。 (另见glob模块。)

编写辅助函数:

import fnmatch
import os

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

并按如下方式使用:

result = listdir("./sources", "*.c")

答案 6 :(得分:1)

import os, re
cfile = re.compile("^.*?\.c$")
results = []

for name in os.listdir(directory):
    if cfile.match(name):
        results.append(name)

答案 7 :(得分:1)

shutil.copytree的实现在docs中。我想把它列入INCLUDE。

def my_copytree(src, dst, symlinks=False, *extentions):
    """ I modified the 2.7 implementation of shutils.copytree
    to take a list of extentions to INCLUDE, instead of an ignore list.
    """
    names = os.listdir(src)
    os.makedirs(dst)
    errors = []
    for name in names:
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                my_copytree(srcname, dstname, symlinks, *extentions)
            else:
                ext = os.path.splitext(srcname)[1]
                if not ext in extentions:
                    # skip the file
                    continue
                copy2(srcname, dstname)
            # XXX What about devices, sockets etc.?
        except (IOError, os.error), why:
            errors.append((srcname, dstname, str(why)))
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error, err:
            errors.extend(err.args[0])
    try:
        copystat(src, dst)
    # except WindowsError: # cant copy file access times on Windows
    #     pass
    except OSError, why:
        errors.extend((src, dst, str(why)))
    if errors:
        raise Error(errors)

用法:例如,仅复制.config和.bat文件....

  
    
      

my_copytree(source,targ,'。config','。bat')

    
  

答案 8 :(得分:1)

将目录更改为给定路径,以便您可以搜索目录中的文件。如果您不更改目录,则此代码将搜索当前目录位置中的文件:

import os  #importing os library 
import glob #importing glob library

path=raw_input()  #input from the user 
os.chdir(path)

filedata=glob.glob('*.c') #all files with .c extenstions stores in filedata.
print filedata

答案 9 :(得分:1)

这很干净。 命令来自os库。 该代码将搜索当前工作目录,并仅列出指定的文件类型。您可以通过用目标目录替换'os.getcwd()'来更改它,并通过替换'(ext)'选择文件类型。 os.fsdecode是这样,所以您不会从.endswith()得到字节错误。这也按字母顺序排序,您可以删除原始列表的sorted()。

    import os
    filenames = sorted([os.fsdecode(file) for file in os.listdir(os.getcwd()) if os.fsdecode(file).endswith(".(ext)")])

答案 10 :(得分:0)

如果将'.c'替换为'[.]c$',则会搜索包含.c作为名称的最后两个字符的文件,而不是包含{{1}的所有文件在它之前至少有一个字符。

修改:或者,将cf[-2:]匹配,这可能比提取正则表达式匹配要便宜一些。

答案 11 :(得分:0)

为了清楚起见,如果您想要搜索字词中的点字符,您也可以将其转义:

' * [反斜线] .C'会给你你需要的东西,而且你需要使用类似的东西:

results.append(f),而不是你列出的结果+ = [f]

答案 12 :(得分:0)

此函数返回所有具有指定扩展名的文件名列表:

import os

def listFiles(path, extension):
    return [f for f in os.listdir(path) if f.endswith(extension)]

print listFiles('/Path/to/directory/with/files', '.txt')

如果要在某个目录及其子目录中列出具有指定扩展名的所有文件,您可以这样做:

import os

def filterFiles(path, extension):
    return [file for root, dirs, files in os.walk(path) for file in files if file.endswith(extension)]

print filterFiles('/Path/to/directory/with/files', '.txt')

答案 13 :(得分:0)

这是另一个解决方案,使用 pathlib(和 Python 3):

from pathlib import Path

gamefolder = "path/to/dir"
result = sorted(Path(gamefolder).glob("**.c"))

注意 ** 参数中的双星号 (glob())。这将搜索 gamefolder 及其子目录。如果您只想搜索 gamefolder,请在模式中使用单个 *:“*.c”。有关详细信息,请参阅 documentation

相关问题