用Python遍历文件并搜索文件内容
2007-07-30 09:34
946 查看
上一次用Python的2种方法遍历文件,这次参考了一下Python Promgramming 3rd 里面的代码,用os.path.walk来遍历文件,并且搜索文件里面的内容
search_content.py
import os, sys
listonly = False
skipexts = ['.gif', '.exe', '.pyc', '.o', '.a','.dll','.lib','.pdb','.mdb'] # ignore binary files
def visitfile(fname, searchKey): # for each non-dir file
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
def visitor(args, directoryName,filesInDirectory): # called for each dir
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)
windows调试通过!
search_content.py
import os, sys
listonly = False
skipexts = ['.gif', '.exe', '.pyc', '.o', '.a','.dll','.lib','.pdb','.mdb'] # ignore binary files
def visitfile(fname, searchKey): # for each non-dir file
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
def visitor(args, directoryName,filesInDirectory): # called for each dir
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)
windows调试通过!
相关文章推荐
- Python os.path.walk遍历文件,搜索文件里面的内容
- Python os.path.walk遍历文件,搜索文件里面的内容
- python实现的用于搜索文件并进行内容替换的类实例
- python实现搜索文本文件内容脚本
- Python遍历目录和搜索文件中的关键字
- python 遍历所有文件文件夹,并且搜索其中的字符串
- Python 多线程搜索txt文件的内容,并写入搜到的内容(Lock)
- python学习笔记之os.walk()实现遍历文件搜索字符串
- python 遍历指定文件夹下的所有文件内容
- Python脚本程序实现搜索文本文件内容
- Python遍历文件和内容
- Python---对html文件内容进行搜索取出特定URL地址字符串,保存成列表,并使用每个url下载图片,并保存到硬盘上,使用正则re
- 用os.path.walk来遍历文件,并且搜索文件里面的内容
- Python脚本- 递归遍历文件夹,获取指定扩展名文件,修改文件内容
- Python---对html文件内容进行搜索取出特定URL地址字符串,保存成列表,并使用每个url下载图片,并保存到硬盘上,使用bs4,beautifulsoup模块
- Python脚本程序实现搜索文本文件内容
- python遍历文件及其替换文件内容
- 输出文件中不包含指定的多个排除词的行内容(双重遍历) 分类: python 小练习 2013-11-22 15:20 605人阅读 评论(0) 收藏
- python 学习记录(11)-文件处理/读取文件/文件写入内容/文件删除/文件复制/文件重命名/后缀名/内容查找与替换/文件比较/ 配置文件访问/目录创建与删除/遍历目录/定向输出
- python实现的用于搜索文件并进行内容替换的类实例