Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a number of random lines from a file in Python

Tags:

python

Could someone show me how I could read a random number of lines from a file in Python?

like image 486
Mridang Agarwalla Avatar asked Nov 05 '10 12:11

Mridang Agarwalla


1 Answers

Your requirement is a bit vague, so here's another slightly different method (for inspiration if nothing else):

from random import random
lines = [line for line in open("/some/file") if random() >= .5]

Compared with the other solutions, the number of lines varies less (distribution around half the total number of lines) but each line is chosen with 50% probability, and only one pass through the file is required.

like image 153
SimonJ Avatar answered Nov 12 '22 00:11

SimonJ