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