这是我所拥有的:
glob(os.path.join('src','*.c'))
但是我想搜索src的子文件夹。这样做是可行的:
glob(os.path.join('src','*.c'))
glob(os.path.join('src','*','*.c'))
glob(os.path.join('src','*','*','*.c'))
glob(os.path.join('src','*','*','*','*.c'))
但这显然是有限和笨拙的。
这是我所拥有的:
glob(os.path.join('src','*.c'))
但是我想搜索src的子文件夹。这样做是可行的:
glob(os.path.join('src','*.c'))
glob(os.path.join('src','*','*.c'))
glob(os.path.join('src','*','*','*.c'))
glob(os.path.join('src','*','*','*','*.c'))
但这显然是有限和笨拙的。
当前回答
下面是我的解决方案,使用列表理解在一个目录和所有子目录中递归地搜索多个文件扩展名:
import os, glob
def _globrec(path, *exts):
""" Glob recursively a directory and all subdirectories for multiple file extensions
Note: Glob is case-insensitive, i. e. for '\*.jpg' you will get files ending
with .jpg and .JPG
Parameters
----------
path : str
A directory name
exts : tuple
File extensions to glob for
Returns
-------
files : list
list of files matching extensions in exts in path and subfolders
"""
dirs = [a[0] for a in os.walk(path)]
f_filter = [d+e for d in dirs for e in exts]
return [f for files in [glob.iglob(files) for files in f_filter] for f in files]
my_pictures = _globrec(r'C:\Temp', '\*.jpg','\*.bmp','\*.png','\*.gif')
for f in my_pictures:
print f
其他回答
我修改了glob模块,以支持**的递归配色,例如:
>>> import glob2
>>> all_header_files = glob2.glob('src/**/*.c')
https://github.com/miracle2k/python-glob2/
当你想为你的用户提供使用**语法的能力时很有用,因此os.walk()本身不够好。
你需要使用操作系统。行走以收集符合条件的文件名。例如:
import os
cfiles = []
for root, dirs, files in os.walk('src'):
for file in files:
if file.endswith('.c'):
cfiles.append(os.path.join(root, file))
除了建议的答案,你还可以用一些惰性生成和列表理解魔法来做到这一点:
import os, glob, itertools
results = itertools.chain.from_iterable(glob.iglob(os.path.join(root,'*.c'))
for root, dirs, files in os.walk('src'))
for f in results: print(f)
除了适合一行并避免内存中不必要的列表之外,这还有一个很好的副作用,你可以以类似于**操作符的方式使用它,例如,你可以使用os.path。Join (root, 'some/path/*.c')以获取SRC所有子目录下具有此结构的所有。c文件。
我修改了这篇文章最上面的答案。最近创建了这个脚本,它将循环遍历给定目录(searchdir)中的所有文件和它下面的子目录…并打印文件名、根目录、修改/创建日期和大小。
希望这能帮助到某人…他们可以遍历目录,得到fileinfo。
import time
import fnmatch
import os
def fileinfo(file):
filename = os.path.basename(file)
rootdir = os.path.dirname(file)
lastmod = time.ctime(os.path.getmtime(file))
creation = time.ctime(os.path.getctime(file))
filesize = os.path.getsize(file)
print "%s**\t%s\t%s\t%s\t%s" % (rootdir, filename, lastmod, creation, filesize)
searchdir = r'D:\Your\Directory\Root'
matches = []
for root, dirnames, filenames in os.walk(searchdir):
## for filename in fnmatch.filter(filenames, '*.c'):
for filename in filenames:
## matches.append(os.path.join(root, filename))
##print matches
fileinfo(os.path.join(root, filename))
import os
import fnmatch
def recursive_glob(treeroot, pattern):
results = []
for base, dirs, files in os.walk(treeroot):
goodfiles = fnmatch.filter(files, pattern)
results.extend(os.path.join(base, f) for f in goodfiles)
return results
Fnmatch提供了与glob完全相同的模式,因此这是glob的绝佳替代品。语义非常接近的Glob。迭代版本(例如生成器),替换glob。Iglob是一个简单的改编(只在执行过程中产生中间结果,而不是扩展一个结果列表到最后返回)。