本文是关于如何用Python os.path.walk方法遍历搜索文件目录内容的操作详解的文章,python 代码中用os.path.walk函数这个python模块的方法来遍历文件,python列出文件夹下的所有文件并找到自己想要的内容。
文中使用到了Python os模块和Python sys模块,这两个模块具体的使用方法请参考玩蛇网相关文章阅读。
Python os.path.walk方法遍历文件搜索内容方法代码如下:
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方法遍历搜索文件内容的操作详解,文章所用到的模块方法相关文章推荐:
Python OS模块;
Python sys模块;
Python import语句导入模块语法;
玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/code/c2667.html
相关文章 Recommend