简体   繁体   中英

How to read next word or words till next line from file in python?

i'm trying to read words from a line after matching words :

To be exact - I have a file with below texts:

-- Host: localhost
-- Generation Time: Nov 15, 2006 at 09:58 AM
-- Server version: 5.0.21
-- PHP Version: 5.1.2

I want to search that, if that file contains 'Server version:' sub string, if do then read next characters after 'Server version:' till next line, in this case '5.0.21'.

I tried the following code, but it gives the next line(-- PHP Version: 5.1.2) instead of next word (5.0.21).

with open('/root/Desktop/test.txt', 'r+') as f:
    for line in f:
        if 'Server version:' in line:
            print f.next()

You might want to replace that text like this

if 'Server version: ' in line:
    print line.rstrip().replace('-- Server version: ', '')

We do line.rstrip() because the read line will have a new line at the end and we strip that.

you are using f.next() which will return the next line. Instead you need:

with open('/root/Desktop/test.txt', 'r+') as f:
    for line in f:
        found = line.find('Server version:')
        if found != -1:
            version = line[found+len('Server version:')+1:]
            print version

You can try using the split method on strings, using the string to remove (ie 'Server version: ' ) as separator:

if 'Server version: ' in line:
    print line.split('Server version: ', 1)[1]

Might be overkill, but you could also use the regular expressions module re :

match = re.search("Server version: (.+)", line)
if match:                # found a line matching this pattern
    print match.group(1) # whatever was matched for (.+ )

The advantage is that you need to type the key only once, but of course you can have the same effect by wrapping any of the other solutions into a function definition. Also, you could do some additional validation.

as you have

line='-- Server version: 5.0.21'

just:

line.split()[-1]

This gives you the last word rather than all the characters after : .

If you want all the characters after :

line.split(':', 1)[-1].strip()

Replace : with other string as needed.

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