简体   繁体   中英

How to use the enumerate function on a txt file?

I am trying to read the Hi.txt file that I previously created on the console but instead of just getting the values from it I'm trying to add the index value next to it using the enumerate function. (Let's assume that the text file has 3 elements in it).

with open('Hi.txt','r') as hello:
    x = hello.read()
    print(x)

From my understanding, this code will iterate through the elements in that txt file like so:

Dave
Jack
Mary

However, when I try something like this:

with open('Hi.txt','r') as hello:
    x = hello.read()
    for i,v in enumerate(x,1):
        print(i,v)

It prints out every character one by one.

Desired output:

1 Dave
2 Jack
3 Mary

You enumerate the file handle itself:

with open('/Hi.txt','r') as hello:
    for i,v in enumerate(hello,1):
        print(i,v, end="")

You can do something like this:

with open('Hi.txt','r') as hello:
    for i,v in enumerate(hello.readlines(), 1):
        print(i,v, end="")

This will iterate for all the lines in your file ( assuming you have all the file items in separated lines ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM