How to return the line number of a line being read from a text file?

Question:

I have a text file (my_file.txt) as follows:

Game of Thrones

Friends

Suits

Hospital Playlist

From this file, I need to choose a random line & return it along with the line number.

For returning a random line, I do:

lines = open('my_file.txt').read().splitlines()
my_random_line = random.choice(lines)

But how can I get the info about the line number of the line?

Example:

If the line returned is Suits, the number of the line should be: 3

Asked By: reinhardt

||

Answers:

You can generate the line number randomly, then use it as an index to get the line:

#random integer from 1 to lenth of lines (both inclusive)
line_number = random.randint(1, len(lines))
#subtract one because lists are 0-indexed
my_random_line = lines[line_number-1]
Answered By: Addison Schmidt

Instead of choosing a random line, choose a random number that is within the number of lines. Then return that number and that line.

lines = myfile.readlines()
choice = random.randint(len(lines) - 1)
return choice, lines[choice]
Answered By: John Gordon
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.