Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python實戰:在指定目錄及子目錄中查找符合條件的文件

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
Copyright © Linux教程網 All Rights Reserved