Search code examples
pythonfilereverseenumerate

Reverse only numbers from file


How can I reverse only number and not the text from this ?

datas.txt
Bungo Charlie
Bungo Echo
Bungo Bravo
Bungo Tango
Bungo Alpha
with open('datas.txt', 'r') as f:
    for i, line in enumerate(f):
        print('{}. {}'.format(i+1, line.strip()))

Expectation:

5. Bungo Charlie
4. Bungo Echo
3. Bungo Bravo
2. Bungo Tango
1. Bungo Alpha

What I got :

1. Bungo Charlie
2. Bungo Echo
3. Bungo Bravo
4. Bungo Tango
5. Bungo Alpha

Solution

  • Simply using the reversed() function will reverse everything:

    for i, line in reversed(list(enumerate(f))
    

    If you'd like to only reverse the numbers, you can do it selectively (but messily) like so:

    reversed(list(enumerate(reversed(f))))
    

    If you want something cleaner, you can define a function using zip():

    def reverse_enumerate(x):
        return zip(reversed(range(len(x))), reversed(x))