简体   繁体   中英

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. 'file.txt' is below:

...
func(string=0x41004578, val=0x01)
...
...

So if 'string' matches in file, i want to get '0x41004578' value in return.

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. So, let's do the same except in Python.

with open('file.text', 'r') as fp:
  for line in fp:
    match = re.search('string=([^,]+)', line)
    if match:
      print match.group(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM