The problem is that you are calling sorted once for each line (i.e. inside the loop), not for the entire set of lines. Try this instead:
f1 = open('file.txt','r')
a=sorted(f1.readlines(), key=lambda l:l.split('|')[1])
r=open('file.txt','w')
r.writelines(a)
f1.close