create Fixed Width File in Python


The code below creates one line of string. My problem is i have a big database. From which i have to create a fixed width text file. Which should post multiple lines

And below code example only posts one line.

can anyone help with code that post multiple line in a flatfile

class FixWidthFieldLine(object):

    fields = (('foo', 10),
              ('bar', 30),
              ('ooga', 30),
             ('booga', 10))

    def __init__(self): = '' = ''
        self.ooga = ''
        self.booga = ''

    def __str__(self):
        return ''.join([getattr(self, field_name).ljust(width) 
                    for field_name, width in self.fields])

f = FixWidthFieldLine() = 'hi' = 'joe'
f.ooga = 'howya'
f.booga = 'doin?'

print f
Asked By: Nayana Mahajan



You might use formatting e.g. .format for your task following way, say you want to have widths 10, 15, 10 then you might do

data = (('Able','Baker','Charlie'),('Dog','Easy','Fox'),('George','How','Item'))
for row in data:

gives output

Able      Baker          Charlie   
Dog       Easy           Fox       
George    How            Item      
Answered By: Daweo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.