使用python搜索文件中的单词

使用python搜索文件中的单词,python,search,Python,Search,在shell中,cat filename | grep-i error将从包含字符串“error”的文件返回内容 Python与此等价的是什么?打开文件,迭代所有行,仅当其中包含错误时才打印这些行 with open(file) as f: for line in f: if 'error' in line: print(line) 对于不区分大小写的匹配 with open(file) as f: for line in f:

在shell中,cat filename | grep-i error将从包含字符串“error”的文件返回内容


Python与此等价的是什么?

打开文件,迭代所有行,仅当其中包含
错误时才打印这些行

with open(file) as f:
    for line in f:
        if 'error' in line:
            print(line)
对于不区分大小写的匹配

with open(file) as f:
    for line in f:
        if re.search(r'(?i)error', line):
            print(line)

为什么你不能打开文件,逐行读取并打印出其中有
错误的行呢?可能是重复的