python检索特定内容的文本文件实例
作者:wedvefv 时间:2022-12-29 12:05:42
windows环境下python2.7
脚本指定一个参数作为要检索的字符串
例如: >find.py ./ hello
# coding=utf-8
import os
import sys
# 找到当前目录下的所有文本文件
def findFile(path):
f = []
d = []
l = os.listdir(path)
for x in l:
if os.path.isfile(os.path.join(os.getcwd() + "\\", x)):
f.append(x)
else:
d.append(x)
return f, d # 返回文件和目录的列表
# print x, "\n", y
# 统计一个文本内字符串的个数
def findstrCount(file, strToFind):
count = 0
thefile = open(file, 'rb')
while True:
buffer = thefile.read()
if not buffer:
break
count += buffer.count(strToFind)
thefile.close()
return count
# 遍历文件列表中,包含特定字符串的文件
def findstr(file, str):
# f = open(file, "r+")
# if f.read().find(str) != -1:
# s = os.getcwd() + "\\" + file
# else:
# s = "None"
# f.close()
i = 1
global s
for line in open(file):
# return is index of the str start position.
if line.find(str) != -1:
s = os.getcwd() + "\\" + file + "------>line:%d" % (i)
print s
i = i + 1
return s
L = [] # 全局变量,存放找到的目标文件
def find(p, str):
try:
f, d = findFile(p)
for x in f:
Ret = findstr(x, str)
if Ret:
L.append(Ret)
if d:
for x in d:
os.chdir(x)
find("./", str)
os.chdir('../')
except Exception, e:
print e
finally:
pass
if __name__ == '__main__':
s = 0
find(sys.argv[1], sys.argv[2])
来源:https://blog.csdn.net/l_vim11/article/details/53928112
标签:python,检索,文本,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何对MySQL数据库表进行锁定
2009-02-10 10:39:00
python+requests+pytest接口自动化的实现示例
2022-11-01 06:12:27
![](https://img.aspxhome.com/file/2023/2/64302_0s.jpg)
用JAVASCRIPT格式化数字成货币(逗号隔开)
2008-01-30 12:34:00
使用Protocol Buffers的C语言拓展提速Python程序的示例
2022-12-04 08:46:20
asp HTTP_X_FORWARDED_FOR和REMOTE_ADDR
2010-07-02 12:33:00
php 一维数组的循环遍历实现代码
2023-06-12 00:49:04
![](https://img.aspxhome.com/file/2023/9/55469_0s.jpg)
改进SQL Server数据库系统安全五步走
2009-01-20 11:47:00
强大的Perl正则表达式实例详解
2023-08-09 11:12:33
制作主页的独门功夫五十招
2010-09-05 21:15:00
Quickwork For Asp -实战之后台管理
2009-12-31 19:13:00
![](https://img.aspxhome.com/file/UploadPic/20101/11/2010111171421531s.jpg)
彻底终结浏览器Cache页面的解决方案
2008-04-21 15:10:00
确定能够释放空间的SQL Server数据库文件的脚本
2010-07-31 12:36:00
![](https://img.aspxhome.com/file/UploadPic/20107/31/2010731132357283s.jpg)
javascript新闻图片轮换类
2009-01-09 12:57:00
文章关键字替换带链接需要注意的两个问题
2010-02-25 12:18:00
System.Runtime.InteropServices.COMException的解决方法
2023-07-18 15:03:27
php bugs代码审计基础详解
2023-06-02 13:49:52
![](https://img.aspxhome.com/file/2023/6/55366_0s.png)
Golang控制通道实现协程等待详解
2023-07-21 16:23:39
window.location.hash的应用及浏览器的支持测试
2009-07-07 11:52:00
![](https://img.aspxhome.com/file/UploadPic/20097/7/hashdemo-57s.png)
长文章自动分页asp实例-支持HTML
2007-10-10 21:29:00
Python中seaborn库之countplot的数据可视化使用
2023-08-10 20:38:56
![](https://img.aspxhome.com/file/2023/6/62026_0s.png)