title: How to get a random line from within a gzip compressed file in python without reading it into memory
body: <p>Let's say I have a 531 gig gzipped textfile with exactly 512 548 457 601 475 lines split by '\n' and wanted to get a random line out of it without filesplitting. (Don't worry, it's not really THAT large; just wanted to state that it's a huge file and I know how many lines it has.)</p>
  
  <p>How I would normally do it with a smaller compressed file:</p>
  
  <pre><code>import fileinput
  import gzip
  import random
  
  list = []
  
  for line in fileinput.input(file, openhook=gzip.open):
      list.append(line)
  
  listLength = len(list)
  randomListLineOne = line[random.randint(0, listLength)]
  randomListLineTwo = line[random.randint(0, listLength)]
  ...
  </code></pre>
  
  <p>What I've found on the topic:</p>
  
  <p><a href="https://stackoverflow.com/questions/3540288/how-do-i-read-a-random-line-from-one-file-in-python">How do I read a random line from one file in python?</a></p>
  
  <pre><code>import random
  
  def random_line(afile):
      line = next(afile)
      for num, aline in enumerate(afile):
        if random.randrange(num + 2): continue
        line = aline
      return line
  </code></pre>
  
  <p>Waterman's "Reservoir Algorithm" translated by Alex Martelli from Knuth's "The Art of Computer Programming"</p>
  
  <p>Could you adapt this for compressed files? I tried setting my compressed file as afile but that didn't work.
  Or is there another (easier) way to achieve this?</p>