[Tutor] Create a table by writing to a text file.

Steven D'Aprano steve at pearwood.info
Wed Feb 22 15:34:37 CET 2012


David Craig wrote:

> I have been trying to write them to a text file but it is difficult to 
> organise them into rows and columns with appropriate spacing to make it 
> readable. I would like something like,
> 
> Stations   Station1         Station2
> Station1       0.0            33.57654
> Station2      33.57654       0.0
[...]
> I've tried adding spaces but to some of the values (i.e. '0.0            
> ') but this is very messy.

Try using string formatting strings. E.g.:

print "%s %8.2f %8.2f" % ("station1", 0, 4)


will produce this output:

station1     0.00     4.00


Naturally you don't have to pass the resultant string to print. You can store 
it in a variable, and write it to a file:

line = "%s %8.2f %8.2f" % ("station1", 0, 4)
myfile.write(line + '\n')



The format string codes cover a lot of options. Each code starts with a % 
sign, and ends with a letter s, d, f, and a few others.

%s  string
%d  decimal number
%f  floating point number
%%  use a literal percentage sign
plus others

Inside the format target, you can add optional terms for the field width, 
number of decimal points, etc. A few examples:

%8.2f  Pad the number to a total width of 8 (or more if necessary),
        using two figures after the decimal place. The number is
        right-justified and padded on the left with spaces.


%-4.1f Pad the number to a total width of 4 (or more if necessary),
        using one figure after the decimal place. The number is
        left-justified and padded on the right with spaces.

Lots more options here:

http://docs.python.org/library/stdtypes.html#string-formatting-operations


Alternatively, if you have Python 2.6 or newer, you can use the format method:

print "{0} {1:8.2f} {2:8.2f}".format("station1", 0, 4)


will produce this output:

station1     0.00     4.00


See here for more options:

http://docs.python.org/library/string.html#string-formatting



-- 
Steven


More information about the Tutor mailing list