如何从文本文件中读取3个字段并将其写入单行?

时间:2018-03-21 13:35:58

标签: python regex python-2.7

我正在尝试从sample.txt读取3个值,如“IP”,“port”,“name”,并使用下面的给定python代码打印“IP + port + name”:

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()

但我收到以下错误:

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'

有人能提出解决这个问题的线索吗?

1 个答案:

答案 0 :(得分:0)

不使用正则表达式。

<强>演示

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)

<强>输出:

IP:172.2.1.5, Port:2233, Name:test@test1.com
相关问题