python - 如何使用python在另一个文件中搜索文件的每一行?
问题描述
我的expected_cmd.txt(比如f1)是
mpls ldp
snmp go
exit
我的configured.txt(比如f2)是
exit
这是我正在尝试的代码,在 f2 中搜索 f1 的所有行
with open('expected_cmd.txt', 'r') as rcmd, open('%s.txt' %configured, 'r') as f2:
for line in rcmd:
print 'line present is ' + line
if line in f2:
continue
else:
print line
所以基本上我试图从第一个文件中打印第二个文件中不存在的行。但是使用上面的代码,我得到的输出为
#python validateion.py
line present is mpls ldp
mpls ldp
line present is snmp go
snmp go
line present is exit
exit
不知道为什么要打印exit
匹配的内容。
另外我想知道是否有内置函数可以在 python 中执行此操作?
解决方案
with open('%s.txt' %configured,'r') as f2:
cmds = set(i.strip() for i in f2)
with open('expected_cmd.txt', 'r') as rcmd:
for line in rcmd:
if line.strip() in cmds:
continue
else:
print line
这解决了我的问题。
推荐阅读
- cassandra - 针对特定版本的 Cassandra 运行查询
- sql - 如何在存储过程中将一个 CLOB 输出用作另一个 CLOB 中的列?
- sql - 在 Oracle SELECT 查询中,如何更改特定条目的描述?
- javascript - React redux - 将新项目推送到状态数组不起作用
- reinforcement-learning - 设置 config["dueling"]=False 仍然运行 Dueling DQN
- node.js - 节点 api 路由不返回任何状态码
- python - 为什么 `lambda: MyClass()` 是合法的,但 `MyClass()` 本身是非法的?
- java - java.util.Timer 中 timer.schedule() 队列的池大小是多少
- javascript - Javascript编程方式获取两个日期对象之间30分钟间隔的时间
- typescript - 插值字符串类型不能用于索引与键类型相同的记录