import re
with open('base.txt') as file:
for line in file:
pattern = r'^([A-z0-9]*)_([A-z0-9]*)(@.*)?:(.*)$'
newpattern = r'\1_\2\3:\1'
res = re.sub(pattern, newpattern, line)
resfile = open('result.txt', 'a')
resfile.write(res)
resfile.close()