0

I am trying to read 3 values like "IP","port","name" from the sample.txt and print like "IP+port+name" using given python code below:

Sample.txt:

device.IP=172.2.1.5
test1.name=m1234-tsample.test.com
input.port$test=2233
userName=test@test1.com
passwd=test123
nmae=ryan

test.py:

import re

def change_port():
    with open('/Users/test/Desktop/sample.txt', 'rt') as in_file:
        contents = in_file.read()
        result   = re.compile(r'%s.*?%s' % ("IP=", "test1.name="), re.S)
        IP=result.search(contents).group(0)
        result1   = re.compile(r'%s.*?%s' % ("port$test=", "userName"), re.S)
        port= result1.search(contents).group(1)
        result2   = re.compile(r'%s.*?%s' % ("test1.name=", "input.port$test"), re.S)
        name= result2.search(contents).group(2)
        print name+IP+port

change_port()

But I am getting below error:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    change_port()
  File "test.py", line 7, in change_port
    IP=result.search(contents).group(0)
AttributeError: 'NoneType' object has no attribute 'group'

Could anyone give a clue to fix this please?

martineau
  • 119,623
  • 25
  • 170
  • 301
rcubefather
  • 1,534
  • 6
  • 25
  • 49

1 Answers1

0

Without using regex.

demo

s = """device.IP=172.2.1.5
test1.name=m1234-tsample.test.com
input.port$test=2233
userName=test@test1.com
passwd=test123
nmae=ryan"""

IP, port, name = "", "", ""
for i in s.split("\n"):
    if "IP" in i:
        IP = i.split("=")[-1]
    if "port" in i:
        port = i.split("=")[-1]
    if "userName" in i:
        name = i.split("=")[-1]
print "IP:{}, Port:{}, Name:{}".format(IP, port, name)

Output:

IP:172.2.1.5, Port:2233, Name:test@test1.com
Rakesh
  • 81,458
  • 17
  • 76
  • 113