title: Is there a better way to transparently read and write from regular/gzip file or stdin/stdout?
body: <p>I want to write some code which reads from either a file (regular/gzip) or stdin and writes to either a file (regular/gzip) or stdout. What is for you the best solution to this problem?</p>
  
  <p>My solution looks like this so far:</p>
  
  <pre class="lang-py prettyprint-override"><code># read input
  if not args.input:
      outlines = process_lines(sys.stdin, args)
  
  elif args.input.endswith(".gz"):
      with gzip.open(args.input, "r") as infile:
          outlines = process_lines(infile, args)
  
  else:
      with open(args.input, "r") as infile:
          outlines = process_lines(infile, args)
  
  # write output
  if not args.output:
      for line in outlines:
          sys.stdout.write("%s\n" % line)
  
  elif args.output.endswith(".gz"):
      with gzip.open(args.output, "w") as outfile:
          for line in outlines:
              outfile.write("%s\n" % line)
  
  else:
      with open(args.output, "w") as outfile:
          for line in outlines:
              outfile.write("%s\n" % line)
  </code></pre>
  
  <p>What do you think? What would be a better more generic solution?</p>