__daydayup__ 发表于 2014-12-09 17:50

递归匹配文件

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"]

shreychen 发表于 2014-12-09 18:58

def search_files(pattern, search_path):
    cmd = "find {path} -type f -name {pattern}".format(path=search_path, pattern=pattern)
    return :lol:lol:lol

银风冷月 发表于 2014-12-10 10:43

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试试

__daydayup__ 发表于 2014-12-10 13:08

好吧,有更pythoner的实现吗?回复 2# shreychen


   

shreychen 发表于 2014-12-10 13:31

回复 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']

shreychen 发表于 2014-12-10 13:50

其实用os.walk()很容易实现,既然楼主要递归就递归吧.回复 5# shreychen


   

py7th 发表于 2014-12-11 22:09

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
#

j_cle 发表于 2014-12-16 11:21

使用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]
查看完整版本: 递归匹配文件