[英]read a file and search for a string, if matches, return the next word in python
I am very new to python, I am trying to do following operation: Read a given file ('file.txt') and search for a particular string("string") if matches, return the next word. 我是python的新手,我正在尝试执行以下操作:读取给定的文件(“ file.txt”),如果匹配则搜索特定的字符串(“ string”),然后返回下一个单词。 'file.txt' is below:
“ file.txt”如下:
...
func(string=0x41004578, val=0x01)
...
...
So if 'string' matches in file, i want to get '0x41004578' value in return. 因此,如果文件中的“字符串”匹配,我希望得到“ 0x41004578”的值作为回报。
How to do this? 这个怎么做? I am totally blank.
我完全空白。 I am trying following
我正在尝试关注
file = open('file.txt', 'r').read().find('string')
The tool normally used for things like this is grep. 通常用于这种事情的工具是grep。 So, let's do the same except in Python.
因此,除了在Python中,让我们做同样的事情。
with open('file.text', 'r') as fp:
for line in fp:
match = re.search('string=([^,]+)', line)
if match:
print match.group(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.