Python Forum

Full Version: Formatting file data written to file.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have four columns of data in a file created and written to
by a Python script.

The first column is a line entry number beginning with, '1'
with increment by '1' for each additional line written to the
file. The data entries are comma separated.

I would like to right justify the first column but cannot seem
to identify a method which works. The reason for right hand
justification is to make the displayed file output easier to
read. Presently the file output looks like this:

1,    15:45:08.335,    120456321, 80446723
7,    15:47:14.456,    120309625, 80447991
10,    15:50:22.920,    120225771, 80505351
102,    15:59:38.333,    119889999, 80504999
The above formatting makes it difficult to read. What I want
to do is to write the data to the file such that entering the
following: cat filename.txt which contains the above displayed
data will display the data in the format shown below:

  1,    15:45:08.335,    120456321, 80446723
  7,    15:47:14.456,    120309625, 80447991
 10,    15:50:22.920,    120225771, 80505351
102,    15:59:38.333,    119889999, 80504999
I an using the following script to write the results stored in the
four variables to "output_filename":

  with open(output_filename, 'a') as g:
              g.write(str(z)+",   "+time+",    "+velocity1+" , "+velocity2 "\r\n")  
Is there a way to right hand justify the variable entry 'z' through formatting
like is done in the print statement with txt.format.

TIA

Mel
You could use string formatting:
g.write(f'{z:>5}, {time}, {velocity1}, {velocity2}\r\n')
With format method:
g.write('{:>5}, {}, {}, {}\r\n'.format(z, time, velocity1, velocity2))
Here is an overview: pyformat.info
Dead Eye, many thanks and also double thanks for the referral to the pyformat.info