递归匹配文件
tmp/├── a.tpl
├── tmp
│ ├── b.tpl
│ ├── tmp
│ │ ├── c.tpl
│ │ └── tmp
│ │ └── d.tpl
│ └── yy
└── xx希望得到["./tmp/a.tpl","./tmp/tmp/tmp/tmp/d.tpl","./tmp/tmp/tmp/c.tpl","./tmp/tmp/b.tpl"] def search_files(pattern, search_path):
cmd = "find {path} -type f -name {pattern}".format(path=search_path, pattern=pattern)
return :lol:lol:lol import os
l = []
def Dir(indir):
for i in os.listdir(indir):
if os.path.isdir(indir,i):
return Dir(os.path.join(indir,i))
else:
l.append(os.path.join(indir,i))
Dir('.')
print l试试 好吧,有更pythoner的实现吗?回复 2# shreychen
回复 4# __daydayup__ #!/usr/bin/env python
#coding:utf-8
import os,glob
def search_files(pattern,search_path):
if not search_path:
return []
childpathes = []
matches = []
for spath in search_path:
matches +=
for p in os.listdir(spath):
childpath = os.path.join(spath, p)
if os.path.isdir(childpath):
childpathes.append(childpath)
return matches + search_files(pattern, childpathes)
print search_files("*.tpl", ["/tmp/tmp"])结果$ python search.py
['/tmp/tmp/a.tpl', '/tmp/tmp/tmp/b.tpl', '/tmp/tmp/tmp/tmp/c.tpl', '/tmp/tmp/tmp/tmp/tmp/d.tpl'] 其实用os.walk()很容易实现,既然楼主要递归就递归吧.回复 5# shreychen
6楼给出了最方便的思路,很正确,看下简单代码:# python a.py
['/tmp/temp/a.tpl', '/tmp/temp/tmp/b.tpl', '/tmp/temp/tmp/tmp/c.tpl', '/tmp/temp/tmp/tmp/tmp/d.tpl']
# cat a.py
#!/usr/bin/env python
import os
a=[]
for root,dirs,files in os.walk("/tmp/temp/"):
for file in files:
f=os.path.join(root,file)
a.append(f)
print a
#
使用walk 完成的并将输出写到文件中去了
# _*_encoding:utf-8 _*_
from os.path import walk
m='C:\\Users\\User\\Desktop\\test'
filenamelist=[]
def visit(arg,dirname,names,flist=filenamelist):
f=open('C:\\tt.txt','w')
flist +=
# for iin flist[:]:
for i in range(0,len(flist)):
f.write(flist)
print flist
f.close()
walk(m,visit,0)
页:
[1]