-1

I want to use Python to output a random line from an external .txt file. In this .txt file there are several sentences. But each of them is in a different line.

My approach is to generate a random line number:

import random

line = random.randint(1, max_line)

#max_line stands for the number of lines in the .txt file.

and then to reproduce this line using print().

I've already looked around a bit, but haven't found anything yet regarding outputting the sentence of the line. Any idea how I could make this work?

JueK3y
  • 267
  • 9
  • 22

1 Answers1

0

I think what you want to use is .readlines(). This could work like this:

line = random.randint(1, max_line)

with open("external_file.txt", "r") as file:
    print(file.readlines()[line]

Replace "external_file.txt" with your actual filename.

Although, if you want to include the first line of the file as well, you might want to change line = random.randint(1, max_line)to line = random.randint(0, max_line)

Viggar
  • 140
  • 1
  • 8