Python:查找目录下匹配字符的文件列表

Posted by Leon on 2015-10-23

懒得找相关App就自己写了个脚本来用,看代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#coding=utf-8

#Python搜索目录下匹配 特定字符串 的所有文件
#Created by leon on 15/10/23.
#Copyright (c) 2015年 leon. All rights reserved.

import os,re

# list all files
def listAllFiles(dirPath):
fileList = [];
for root, dirs, files in os.walk(dirPath):
for fileObj in files:
fileList.append(os.path.join(root,fileObj))
return fileList

# search string in each file
def searchFile(filePath, patternStr):
fileText = open(filePath, 'r')
pattern = re.compile(patternStr)

line_index = 1;
for eachLine in fileText:
if re.search(pattern, eachLine):
print filePath, ' > 出现在在第 %d 行, %s' % (line_index, eachLine)
return True;
line_index += 1;
return False;

def main():
searchDir = raw_input('请输入要搜索的目录:>')
patternStr = raw_input('请输入要搜索的字符串(支持正则): >')
fileList = listAllFiles(searchDir)
find_count = 0;
for _file in fileList:
if(searchFile(_file, patternStr)):
find_count += 1;
raw_input('搜索完毕, 共搜到 %d 个匹配 "%s" 的文件.' % (find_count, patternStr))
if __name__ == '__main__':
main()

运行效果