0

Possible Duplicate:
Writing nicely formatted text in Python

I have this code for writting a header into the created txt file:

if not os.path.exists('list.txt'):
    f= file('list.txt', 'w')
    f.write ("\t".join("".join (str(row)) for row in header_names.keys()))+"\n")
    f.write ("\n")

And this is the code I use to append new rows to the text file:

f = open("list.txt","a")

f.write ("\t".join("".join (str(row)) for row in header_names.values()))+"\n")
f.write ("\n")
f.close()

The output that get's written in the text file isn't as I want it do be:

Name    some number some number2    % percentage    average
Test    2   2   100.0   0.4
TestTestTest    3   4   75.0    0.49
tes 2   3   66.67   0.33

I would like something like this:

Name           some number  some number2    % percentage    average
Test           2            2               100.0           0.4
Test           2            2               100.0           0.4
TestTestTest   3            4               75.0            0.49
tes            2            3               66.67           0.33

Is there any simple way to achieve this. It it's not mandatory it's written into the txt like that, but the output from reading should....

Cœur
  • 37,241
  • 25
  • 195
  • 267
user1509923
  • 193
  • 1
  • 3
  • 13

1 Answers1

3

Format each column to a certain width, for instance:

>>> header = ['one', 'two', 'three']
>>> print [format(el, '<30') for el in header]
['one                           ', 'two                           ', 'three                         ']
>>> print ''.join(format(el, '<30') for el in header)
one                           two                           three                         
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • 1
    @user1509923 Look at the "Aligning the text and specifying a width:" section of [this doc page](http://docs.python.org/2/library/string.html#format-examples) to see different formatting examples. – Matthew Adams Dec 16 '12 at 19:39
  • Thank you, i'm learing new things every day :D – user1509923 Dec 16 '12 at 19:48