Could someone show me how I could read a random number of lines from a file in Python?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With