1

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)
accdias
  • 5,160
  • 3
  • 19
  • 31
Voltz
  • 25
  • 4
  • 1
    Are you on Linux? If so, [this post](https://unix.stackexchange.com/questions/248155/how-to-sort-blocks-of-lines-with-a-specific-line-from-the-block) can be a better alternative. Or maybe [this other one](https://stackoverflow.com/questions/16114731/how-to-sort-with-linux-command-while-treat-3-lines-as-1-block-and-sort-based-on). – accdias Dec 13 '22 at 19:46
  • First step: https://stackoverflow.com/questions/68037642/how-to-split-a-file-by-every-n-lines – mkrieger1 Dec 13 '22 at 19:48

1 Answers1

1

You can try:

with open("input.txt", "r") as f_in:
    data = [line for line in map(str.strip, f_in) if line]

data = sorted(
    [data[i : i + 4] for i in range(0, len(data), 4)], key=lambda k: k[0]
)

with open("output.txt", "w") as f_out:
    for chunk in data:
        print(*chunk, file=f_out, sep="\n")

This creates output.txt with contents:

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
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91