Pythonでファイル検索
あるフォルダ配下のExcelファイルのうち、特定の文字列を含むファイルだけ抜き出すスクリプトを書いた。
コマンドライン引数にファイル名、探す文字列をセットして実行すると、標準出力に該当ファイル名を表示する。
参考 http://www.python-izm.com/contents/external/xlrd.shtml
http://d.hatena.ne.jp/y_n_c/20100213/1266063968
#!/usr/bin/env python #-*- coding: utf-8 -*- import os import sys import xlrd class BaseFile(object): def _read_file(self, file_path): pass def get_result(self, word, file_path): if self._read_file(file_path).find(word) != -1: return True return False class Text(BaseFile): def __init__(self): self.ext = '.txt' def _read_file(self, file_path): f = open(file_path) str = f.read() f.close() return str class Excel(BaseFile): def __init__(self): self.ext = '.xls' def _read_file(self, file_path): cells = [] book = xlrd.open_workbook(file_path) for sheet in book.sheets(): for col in range(sheet.ncols): for row in range(sheet.nrows): cells.append(sheet.cell(row, col).value) return '/n'.join(cells) if __name__ == '__main__': if len(sys.argv) < 3: print 'Usage python greap_file.py <Mode> <Word>' exit() #引数に応じてインスタンス化 serch_file_class = globals().get(sys.argv[1].capitalize(), None) serch_file = None if serch_file_class: serch_file = serch_file_class() else: print 'Usage <Mode> is text or excel' exit() find_list = [] for path, sub_dirs, files in os.walk('.'): for file in files: file_path = ''.join([path, '/', file]) if file[-len(serch_file.ext):] == serch_file.ext: if serch_file.get_result(sys.argv[2], file_path): find_list.append(file_path) print '\n'.join(find_list)
58行目の'/'を'\\'に変更しないと普通のWindows環境では動かないかも。
コマンドライン引数を変更してtxtファイルも探せる。
この部分は組み込み関数globals()を使用して動的にインスタンス化している。
参考 http://docs.python.jp/2.5/lib/built-in-funcs.html
まぁtxtファイルを探す場合は、シェルから find, grepかけた方がいいと思うけど……
参考 http://open-groove.net/linux-command/find-xargs-grep/
- 作者: Alex Martelli,Anna Martelli Ravenscroft,David Ascher,鴨澤眞夫,當山仁健,吉田聡,吉宗貞紀
- 出版社/メーカー: オライリー・ジャパン
- 発売日: 2007/06/26
- メディア: 大型本
- 購入: 11人 クリック: 423回
- この商品を含むブログ (84件) を見る