代码如下:

1 # 编辑者:闫龙

2 def grep(FindWhat):

3 f=open("a.txt","r",encoding="utf8")#以只读的方式打开a.txt文件

4 while True:

5 try:

6 fline = next(f).strip()#由于File类型本身就是一个迭代器,所以直接使用next对fline进行循环赋值

7 except StopIteration:#检测Stop告警,遇到迭代器循环结束后跳出循环

8 break

9 if(fline.find(FindWhat)!=-1):#判断fline中是否存在用户输入的内容

10 print(fline)

11 else:

12 continue

13 while True:

14 choice = input("cat a.txt | grep ")

15 grep(choice)#调用grep()方法

 

查看原文