f.write, how can i fix the header at the top of the page?

Viewed 67

I have a python code that gives me several output values and I have created a file where a new row of data can be added every run in the same txt file. the problem is the header is written every run, and I just want to fix the header at the top of the file.

Here is what I have :

with open('Trial.txt', 'a') as fd:
    fd.write('{a:^8}  {b:^8}    {c:^8}      {d:^8}  {e:^8}'.format(a='DIA', b='Dia', c='Len',d='PRO',e='time'))
    fd.write("\r")
    fd.write(f'    {magnitude}          {diameter}        {Length}      {Pro_code}     {Time}')
    fd.write("\r\n") 

the output comes in this way:

    DIA            Dia           Len           PRO           time
    8.0            7000          500      0.0052297            141
    DIA            Dia           Len           PRO           time
    7.0            6000          400      0.003237            161

Here is what I am trying to get:

    DIA            Dia           Len           PRO           time
    8.0            7000          500      0.0052297           141
    7.0            6000          400      0.003237            161
1 Answers

Since you open the file in append mode you should write the header only if the file is newly created. For that you can use the tell method of the file object and check if it's at position 0 to tell if it's a new file, and only write the header if it is:

with open('Trial.txt', 'a') as fd:
    if fd.tell() == 0:
        fd.write('{a:^8}  {b:^8}    {c:^8}      {d:^8}  {e:^8}\r\n'.format(a='DIA', b='Dia', c='Len',d='PRO',e='time'))
    fd.write(f'    {magnitude}          {diameter}        {Length}      {Pro_code}     {Time}\r\n')
Related