2

I am trying a program where it has to parse the text file:qwer.txt and print the value before '=' and after ',':

qwer.txt

john.xavier=s/o john
jane.victory=s/o ram

output:

 xavier
 victory

My program shows the entire line,please help on how to display specific text after . and =

with open("qwer.txt", 'r') as my_file:
     a = my_file.readlines()
     for line in a:
        for part in line.split():
             if "=" in part:
                print part.split(' ')[-1]

Please help! answers will be appreciated.

2
  • It would help if you were actually splitting the string on a character in for part in line.split() (4th line in your example) Commented Jul 11, 2014 at 13:55
  • I expect you should probably have a .split(".") somewhere... Commented Jul 11, 2014 at 13:57

3 Answers 3

4
with open("qwer.txt", 'r') as my_file:
    for line in my_file:
        print line.split('=')[0].split('.')[1]
Sign up to request clarification or add additional context in comments.

3 Comments

i get output but also error as : print line.split('=')[0].split('.')[1] IndexError: list index out of range >>>
@adarshram It might be because there might not be a '.' in the name mentioned.
OK, you can add if ('=' in line) and ('.' in line): to check the string is applied for expected condition.
0

You might need to understand the with statement better :-)

Here is my solution:

with open("qwer.txt", 'r') as my_file:
for line in my_file:
    name = line.split("=", 1)[0]
    print name.split(".")[-1]

The two lines can be combines like this as well:

print line.split("=", 1)[0].split(".")[-1]

The official doc of "with" statement is here

Comments

0

Fun little way using regex rather than splitting, and will ignore bad lines rather than erroring (pretty slick if I do say so myself). Also gives you a nice list of names if you want to use them further rather than outputting.

import re

r = re.compile('.+?\.(.+)?\=.+')

with open("qwer.txt", 'r') as f:
    names = [r.match(x).group(1) for x in f.read().splitlines() if r.match(x)]

for name in names: print name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.