Python: File formatting
Question: I have a for loop which references a dictionary and prints out the value
associated with the key. Code is below:

    
    
    for i in data:
        if i in dict:
            print dict[i],
    

How would i format the output so a new line is created every 60 characters?
and with the character count along the side for example:

> 0001 MRQLLLISDLDNTWVGDQQALEHLQEYLGDRRGNFYLAYATGRSYHSARELQKQVGLMEP  
>  0061 DYWLTAVGSEIYHPEGLDQHWADYLSEHWQRDILQAIADGFEALKPQSPLEQNPWKISYH  
>  0121 LDPQACPTVIDQLTEMLKETGIPVQVIFSSGKDVDLLPQRSNKGNATQYLQQHLAMEPSQ


Answer: It's a finicky formatting problem, but I think the following code:

    
    
    import sys
    
    class EveryN(object):
      def __init__(self, n, outs):
        self.n = n        # chars/line
        self.outs = outs  # output stream
        self.numo = 1     # next tag to write
        self.tll = 0      # tot chars on this line
      def write(self, s):
        while True:
          if self.tll == 0: # start of line: emit tag
            self.outs.write('%4.4d ' % self.numo)
            self.numo += self.n
          # wite up to N chars/line, no more
          numw = min(len(s), self.n - self.tll)
          self.outs.write(s[:numw])
          self.tll += numw
          if self.tll >= self.n:
            self.tll = 0
            self.outs.write('\n')
          s = s[numw:]
          if not s: break
    
    if __name__ == '__main__':
      sys.stdout = EveryN(60, sys.stdout)
      for i, a in enumerate('abcdefgh'):
        print a*(5+ i*5),
    

shows how to do it -- the output when running for demonstration purposes as
the main script (five a's, ten b's, etc, with spaces in-between) is:

    
    
    0001 aaaaa bbbbbbbbbb ccccccccccccccc dddddddddddddddddddd eeeeee
    0061 eeeeeeeeeeeeeeeeeee ffffffffffffffffffffffffffffff ggggggggg
    0121 gggggggggggggggggggggggggg hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
    0181 hhhhhhh
    

