Retrieve 10 random lines from a file

numpy, python

Solution

If you know that your file is exactly 10k lines long then you can use linecache:

import random
import linecache

def random_lines(filename)
    idxs = random.sample(range(10000), 10)
    return [linecache.getline(filename, i) for i in idxs]

This returns a list with 10 random lines which you can print with:

for line in random_lines('file.txt'):
    print(line)

Problem

I have a text file which is 10k lines long and I need to build a function to extract 10 random lines each time from this file. I already found how to generate random numbers in Python with numpy and also how to open a file but I don't know how to mix it all together. Please help.

Original source