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

Time:12-14

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
[email protected]
Bob Street 121
Alex Ericsson
1233213211
[email protected]
Alex Street 112
Chris Philips
018207129387
[email protected]
Christ Street 902

When sorted, it should be something like this:

Alex Ericsson
1233213211
[email protected]
Alex Street 112
Bob Steven
02847661723
[email protected]
Bob Street 121
Chris Philips
018207129387
[email protected]
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)

CodePudding user response:

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
[email protected]
Alex Street 112
Bob Steven
02847661723
[email protected]
Bob Street 121
Chris Philips
018207129387
[email protected]
Christ Street 902

CodePudding user response:

s = """Bob Steven
02847661723
[email protected]
Bob Street 121
Alex Ericsson
1233213211
[email protected]
Alex Street 112
Chris Philips
018207129387
[email protected]
Christ Street 90"""


data = '\n'.join(['\n'.join(x) for x in sorted([s.split('\n')[i:i 4] for i in range(0, len(s.split('\n')), 4)], key=lambda x: x[0])])
print(data)

output:

Alex Ericsson
1233213211
[email protected]
Alex Street 112
Bob Steven
02847661723
[email protected]
Bob Street 121
Chris Philips
018207129387
[email protected]
Christ Street 90
  • Related