I am trying to sort a text file in alphabetical order (names) but I still want the information regarding the specific persons to follow with the reordering. I know it sounds weird, but an example might help.
Every person has two names, a phone number, en email address, and an address. When I sort the file, I want the information about every specific person to follow with them.
Text file:
Bob Steven
02847661723
Bob@mail.com
Bob Street 121
Alex Ericsson
1233213211
Alex@mail.com
Alex Street 112
Chris Philips
018207129387
Chris@mail.com
Christ Street 902
When sorted, it should be something like this:
Alex Ericsson
1233213211
Alex@mail.com
Alex Street 112
Bob Steven
02847661723
Bob@mail.com
Bob Street 121
Chris Philips
018207129387
Chris@mail.com
Christ Street 902
I found this string of code which kind of works, but it sorts every single line. How do I make it so it only sorts every 4th line (1st line, 5th line and so on)?
input_filename = "filename.txt"
output_filename = "filename.txt"
with open(input_filename, "r") as f:
l = [line for line in f if line.strip()]
l.sort(key=lambda line: line.split())
with open(output_filename, "w") as f:
for line in l:
f.write(line)