【发布时间】:2015-09-27 07:20:26
【问题描述】:
在 shell 中,cat 文件名 | grep -i error 将从具有字符串 'error' 的文件中返回内容。
什么是 Python 等价物?
【问题讨论】:
-
为什么不能直接打开文件逐行读取,然后打印出带有
error的行? -
Grep and Python的可能重复
在 shell 中,cat 文件名 | grep -i error 将从具有字符串 'error' 的文件中返回内容。
什么是 Python 等价物?
【问题讨论】:
error的行?
打开文件,遍历所有行并仅打印包含error 的行。
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)
【讨论】: