Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I alphabetically sort every -n line in a text file, and have the remaining information follow along?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading