2014-11-14 33 views
0

刚开始使用python,所以如果我听起来很厚,那么请原谅。在python中搜索file.readlines()中的子串

假设以下输入:
my_file内容:

我们爱独角兽
我们爱啤酒
我们爱自由(一种免费的啤酒)

我期待有以下返回true:

# my_file = some path to valid file 
with open(my_file) as f: 
    lines = f.readlines() 
    if 'beer' in lines: 
     print("found beer") # this does not happen 

还是我太习惯于使用C#的方式,在这之后我搜集所有匹配的行:

// assuming I've done a similar lines = open and read from file 
var v = from line in lines 
     where line.Contains("beer") 
     select line; 

会是什么pythonian等同于获取那些持有beer例如线?

回答

1

您已经接近,您需要检查每行中的子字符串,而不是行列表中。

with open(my_file) as f: 
    for line in f: 
     if 'beer' in line: 
      print("found beer") 

举个例子,

lines = ['this is a line', 'this is a second line', 'this one has beer'] 

这第一种情况基本上就是你正在尝试做的

>>> 'beer' in lines 
False 

这就是我上面显示的代码会做

>>> for line in lines: 
     print('beer' in line) 

False 
False 
True 
+0

是的,我已经想通了,我还需要第二次循环中......既然'readlines方法()'基本上返回线与'\ N'追加......感觉很奇怪,我不能使用它......想知道如果“打开(my_file).readlines()作为行:'会工作...但它不会... – Noctis 2014-11-14 12:59:04

1

这就是你怎么做:

with open(my_file) as f: 
    data = f.read() # reads everything to a string 
    if 'beer' in data: 
     print("found beer") 

或更有效地:

with open(my_file) as f: 
    for line in f: 
     if 'beer' in line: 
      print("found beer") 
+0

第一个选项是不是我想要的。我实际上是在寻找特定的线路。我喜欢第二个,但是......并不知道我可以跳过'readlines()'... – Noctis 2014-11-14 12:59:56