Search code examples
pythonenumeration

How to add line numbers to a printed table


I have a text file which is called score.txt, the contents are:

dave 100
ben 50
mary 5
hello 75
elwin 360
didier 1000
ken 85
jibril 79
heyo 900
alan 23
wy 57
sam 99

I am using this code:

with open ("score.txt") as f:
    for line in reversed(sorted([line.rstrip().split() for line in f],key=lambda x : int(x[1]) )):
        d=("\t".join(line))
        print(d)

with open("scoreboard_sorted.txt","a") as file:
    file = file.write(d+"\n")

with open("scoreboard_sorted.txt") as myfile:
    output=myfile.readlines()[0:10]
    print(output)

the results are like this in scoreboard_sorted.txt:

didier  1000
heyo    900
elwin   360
dave    100
sam     99
ken     85
jibril  79
hello   75
wy      57
ben     50
alan    23
mary    5

and for the code:

with open("scoreboard_sorted.txt") as myfile:
    output=myfile.readlines()[0:10]
    print(output)

The result are:

['didier\t1000\n', 'heyo\t900\n', 'elwin\t360\n', 'dave\t100\n', 'sam\t99\n', 'ken\t85\n', 'jibril\t79\n', 'hello\t75\n', 'wy\t57\n', 'ben\t50\n']

ok so the problem is i want it to print like this:

1. didier   1000
2. heyo     900
3. elwin    360
4. dave     100
5. sam      99
6. ken      85
7. jibril   79
8. hello    75
9. wy       57
10.ben      50

Should I add a counter inside?


Solution

  • Assuming the content is in file "txt", following code should work in python. (though it does not preserve the whitespaces)

    with open ("txt") as f:
        for line in sorted(
            [line.rstrip().split() for line in f],
            key=lambda x : int(x[1])
        ):
            print(" ".join(line))
    

    Simply, in cmdline you can do something like below, while preserving white spaces

    sort -k 2 -g txt