如何用Python os.path.walk方法遍历搜索文件内容的操作详解
展开全部
文中使用到了Python os模块和Python sys模块,这两个模块具体的使用方法请参考玩蛇网相关文章阅读。
Python os.path.walk方法遍历文件搜索内容方法代码如下:
?
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
41
import os, sys
#代码中需要用到的方法模块导入
listonly = False
skipexts = ['.gif', '.exe', '.pyc', '.o', '.a','.dll','.lib','.pdb','.mdb'] # ignore binary files
def visitfile(fname, searchKey):
global fcount, vcount
try:
if not listonly:
if os.path.splitext(fname)[1] in skipexts:
pass
elif open(fname).read().find(searchKey) != -1:
print'%s has %s' % (fname, searchKey)
fcount += 1
except: pass
vcount += 1
#www.iplaypy.com
def visitor(args, directoryName,filesInDirectory):
for fname in filesInDirectory:
fpath = os.path.join(directoryName, fname)
if not os.path.isdir(fpath):
visitfile(fpath,args)
def searcher(startdir, searchkey):
global fcount, vcount
fcount = vcount = 0
os.path.walk(startdir, visitor, searchkey)
if __name__ == '__main__':
root=raw_input("type root directory:")
key=raw_input("type key:")
searcher(root,key)
print 'Found in %d files, visited %d' % (fcount, vcount)
Python os.path.walk方法遍历文件搜索内容方法代码如下:
?
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
41
import os, sys
#代码中需要用到的方法模块导入
listonly = False
skipexts = ['.gif', '.exe', '.pyc', '.o', '.a','.dll','.lib','.pdb','.mdb'] # ignore binary files
def visitfile(fname, searchKey):
global fcount, vcount
try:
if not listonly:
if os.path.splitext(fname)[1] in skipexts:
pass
elif open(fname).read().find(searchKey) != -1:
print'%s has %s' % (fname, searchKey)
fcount += 1
except: pass
vcount += 1
#www.iplaypy.com
def visitor(args, directoryName,filesInDirectory):
for fname in filesInDirectory:
fpath = os.path.join(directoryName, fname)
if not os.path.isdir(fpath):
visitfile(fpath,args)
def searcher(startdir, searchkey):
global fcount, vcount
fcount = vcount = 0
os.path.walk(startdir, visitor, searchkey)
if __name__ == '__main__':
root=raw_input("type root directory:")
key=raw_input("type key:")
searcher(root,key)
print 'Found in %d files, visited %d' % (fcount, vcount)
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询