To read a random line from a file in Python, you can use the Python random module with the read() and splitlines() functions.
import random
with open("example.txt","r") as file:
lines = file.read().splitlines()
print(random.choice(lines))
When working with files, the ability to easily extract different pieces of information can be very valuable.
One such piece of information is the ability to get a random line from a file.
We can use the Python random module to help us get a random line from a file.
To get all of the lines in a file, first use the read() and splitlines() functions.
Then, you can use the random.choice() function to get a random line from the file.
Below is a simple example showing you how to get a random line from a file in Python.
import random
with open("example.txt","r") as file:
lines = file.read().splitlines()
print(random.choice(lines))
Reading Multiple Random Lines from File Using Python
If you want to read multiple random lines from file in Python, we can make a slight modification to the code from above.
Let’s say for example you want to read a handful of lines randomly from a file using Python.
Instead of using random.choice(), you should use random.sample() and pass the number of lines you want to read.
Below is an example showing you how to read multiple lines randomly from a file with Python.
import random
with open("example.txt","r") as file:
lines = file.read().splitlines()
print(random.sample(lines,5))
Hopefully this article has been useful for you to understand how to read a file and get a random line from that file using Python.