python3中提取包含特定字符的行

1、测试

root@PC1:/home/test# ls
a.txt  test.py
root@PC1:/home/test# cat a.txt  ## 测试数据
a 3 d
s 1 j
z c m
q e i
3 4 k
h f 3
root@PC1:/home/test# cat test.py
import sys
import importlib
importlib.reload(sys)

fp = open("/home/test/a.txt", "r")
sample = fp.readlines()

file=open("/home/test/result.txt", "w")

for line in sample:
    line = line.strip()
    if '3' in line:            ## 提取包含3的行
        file.write(line)
        file.write('\n')
    if 'm' in line:            ## 提取包含m的行
        file.write(line)
        file.write('\n')
fp.close()
root@PC1:/home/test# python3 test.py      ## 运行程序
root@PC1:/home/test# ls
a.txt  result.txt  test.py
root@PC1:/home/test# cat result.txt
a 3 d
z c m
3 4 k
h f 3
原文地址:https://www.cnblogs.com/liujiaxin2018/p/15579759.html