get random line from file python 1

get random line from file python

import random
lines = open('file.txt').read().splitlines() # creates a list with one line per iteù
randomLine =random.choice(lines) # pick up a random item in this list

Here is what the above code is Doing:
1. open(‘file.txt’) opens the file and returns a file object.
2. .read() reads the file and returns a string containing the contents of the file.
3. .splitlines() splits the string into a list of strings, one string per line.
4. random.choice() picks a random item from a list.

Similar Posts