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

1. Python在指定目录及其子目录中查找文件名含有关键字的文件

源码

#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

Python 的详细介绍请点这里
Python 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2015-08/121283.htm
今日推荐