Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to read this Hi.txt file that I earlier created on the console but instead of just taking the values from it I'm attempting 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 knowledge, this code will repeat for those elements in that txt file like so:

Dave

Jack

Mary

However, when I try something similar to 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.

The output:

1 Dave

2 Jack

3 Mary

1 Answer

0 votes
by (36.8k points)

You need to enumerate the file handle itself:

with open('/Hi.txt','r') as hello:

    for i,v in enumerate(hello,1):

        print(i,v, end="")

 If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch

Browse Categories

...