在python的file.readlines()中搜索子字符串

本文关键字:搜索 字符串 python file readlines | 更新日期: 2023-09-27 18:30:33

刚从python开始,所以如果我听起来很厚,请原谅我。

假设以下输入:
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的行?

在python的file.readlines()中搜索子字符串

你很接近,你需要检查每行中的子字符串,而不是在行列表中。

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

这是你这样做的方式:

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")