0

I'm new to python and can't get over this problem. I have to read a text file with values in square brackets like this.

Hello [user], you are connected from [ip]

User: [user] login date: [datetime]

I should read the file, take the text, replace the values between [] and write them to a database preserving newlines(\n).

I tried to read the file line by line but I can't replace the values I need.

with open('message.txt', 'r') as file:
    msg = file.readlines()
    msg = file.replace('[user]', user)

Maybe I'm not using the right approach.

UPDATE: I found this solution, have this text file, message.txt, like this:

Hello [user],
you ip is [ip]
login date [date]

I write this code:

with open('message.txt') as file:
    f = file.readlines()
    newmessage = ''
    user = 'abc'
    ip = '127.0.0.1'
    date = '2019-01-01'
    for i in f:
        if '[user]' in i:
            line = i.replace('[user]', user)
        if '[ip]' in i:
            line = i.replace('[ip]', ip)
        if '[date]' in i:
            line = i.replace('[date]', date)
        newmessage += line
    print(type(newmessage))
    print(newmessage)

The result is this:

<class 'str'>
Hello abc,
you ip is 127.0.0.1
login date 2019-01-01
gboffi
  • 22,939
  • 8
  • 54
  • 85
Aled72
  • 7
  • 2

1 Answers1

0

What you want can be done subclassing string.Template (you can find the docs and the source code in the usual places).

In [1]: from string import Template                                                                                                           
In [2]: class Bracket_template(Template): 
   ...:     delimiter = '[' 
   ...:     pattern = r''' 
   ...:     \[(?: 
   ...:        (?P<escaped>\[) |         # Expression [[ will become [ 
   ...:        (?P<named>[^\[\]\n]+)\] | # [, ], and \n can't be used in names 
   ...:        \b\B(?P<braced>) |        # Braced names disabled 
   ...:        (?P<invalid>)             # 
   ...:     )'''
In [3]: t = Bracket_template('''Hello [user], you are connected from [ip] 
   ...: User: [user] login date: [datetime]''')                                                                                                                                  
In [4]: data = (('Goofy',  '25.12.20.19', '2019-12-25T00:01'), 
   ...:         ('Mickey', '01.01.20.20', '2020-01-01T11:51'))                                                                                
In [5]: for user, ip, dt in data: 
   ...:     print(t.safe_substitute(user=user, ip=ip, datetime=dt)) 
Hello Goofy, you are connected from 25.12.20.19
User: Goofy login date: 2019-12-25T00:01
Hello Mickey, you are connected from 01.01.20.20
User: Mickey login date: 2020-01-01T11:51

In [6]:                                                                                                                                       
gboffi
  • 22,939
  • 8
  • 54
  • 85