reinhardt
reinhardt

Reputation: 2253

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

Upvotes: 0

Views: 424

Answers (2)

John Gordon
John Gordon

Reputation: 33285

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]

Upvotes: 1

Addison Schmidt
Addison Schmidt

Reputation: 484

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]

Upvotes: 2

Related Questions