Pythonを使ってみたかったので、とりあえず書いてみた。
現在のディレクトリ以下のファイルを検索して、指定の文字列のある行番号を取得する。
なんとなくだけど、いまいちよくわかってない部分があったり。
05 | def get_filepath(rootpath,term): |
07 | for root, dir ,files in os.walk(rootpath): |
08 | for fname in glob.glob(os.path.join(root,term)): |
09 | file_list.append(fname) |
13 | def load_files(file_list): |
15 | for filepath in file_list: |
16 | fname = filepath[filepath.rfind( "/" ) + 1 : len (filepath)] |
17 | f = open (filepath, "r" ) |
18 | file_set.update({fname:f}) |
21 | def close_files(file_set): |
22 | for f in file_set.values(): |
26 | def get_line_number_with_term(file_set,terms): |
28 | for name,f in file_set.items(): |
32 | if (line.find(terms) ! = - 1 ): |
33 | line_number.append(count) |
35 | line_set.update({name:line_number}) |
38 | if __name__ = = '__main__': |
40 | extention = ( "*." + raw_input ( "[ Enter extention ]:" ) ) |
41 | pathList = get_filepath(curdir,extention) |
42 | fileset = load_files(pathList) |
43 | terms = raw_input ( "[ Enter terms ]:" ) |
44 | lineSet = get_line_number_with_term(fileset,terms) |
実行結果
1 | bash -3.2$ python hoge.py |
7 | { 'hoge.py' : [5, 13, 21, 26]} |