Python:在指定目录下查找满足条件的文件

2015-09-26更新:
现在发现要实现如下的功能,完全有现成的命令可以使用:

如递归查找名字含关键字的文件,使用find . -name "*keyword*"
如递归查找内容含关键字的文件,使用grep -Ir keyword .

之前写的程序就当做练手好了 :)


1. 某文件夹递归查找名字含关键字的文件

源码

#search.py
import os
import sys

def search(path, word):
    for filename in os.listdir(path):
        fp = os.path.join(path, filename)
        if os.path.isfile(fp) and word in filename:
            print fp
        elif os.path.isdir(fp):
            search(fp, word)

search(sys.argv[1], sys.argv[2])

使用

python search.py directory_path keyword

2. 某文件夹递归查找内容含关键字的文件

源码

#search.py
import os
import sys

def search(path, word):
    for filename in os.listdir(path):
        fp = os.path.join(path, filename)
        if os.path.isfile(fp):
            with open(fp) as f:
                for line in f:
                    if word in line:
                        print fp
                        break
        elif os.path.isdir(fp):
            search(fp, word)

search(sys.argv[1], sys.argv[2])

使用

python search.py directory_path keyword

3. 参考

http://stackoverflow.com/questions/11162711/find-one-file-out-of-many-containing-a-desired-string-in-python
http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0013868321590543ff305fb9f9949f08d760883cc243812000

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/43816899

/** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://chenzz.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })();