Search code examples
pythontext-files

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


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


Solution

  • 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]