Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我需要迭代文本文件,并在Python3中从和结束条件开始打印特定的文本_Python_Python 3.x - Fatal编程技术网

我需要迭代文本文件,并在Python3中从和结束条件开始打印特定的文本

我需要迭代文本文件,并在Python3中从和结束条件开始打印特定的文本,python,python-3.x,Python,Python 3.x,txt文件示例: vrf X.x.X hello ! how are you ! vrf y.y.y. hi ! 我想浏览上面提供的文本,并从匹配字符串“vrf”开始打印输出,直到匹配字符串“!”。 根据上面的文本,我应该得到如下输出 vrf X.x.X hello vrf y.y.y. hi 使用函数的解决方案: import re with open('lines.txt', 'r') as fh: result = re.findall(r'vrf[^!]+(?=!)', f

txt文件示例:

vrf X.x.X
hello
!
how are you
!
vrf y.y.y.
hi
!
我想浏览上面提供的文本,并从匹配字符串“
vrf
”开始打印输出,直到匹配字符串“
”。 根据上面的文本,我应该得到如下输出

vrf X.x.X
hello
vrf y.y.y.
hi
使用函数的解决方案:

import re

with open('lines.txt', 'r') as fh:
    result = re.findall(r'vrf[^!]+(?=!)', fh.read(), re.M)

print(''.join(result))
输出:

vrf X.x.X
hello
vrf y.y.y.
hi

你尝试了什么?感谢Roman,我得到了我想要打开一个文件并搜索特定的行,从条件开始,也以条件结束..如前所述…不同之处在于,我们被分配了字符串S…我试图从文件中读取行并获得所需的输出..但没有成功!!!