pythonprintingformatfile-writingfilehandle

How to make a custom print format?


I want to print some variables to a file in a custom table format and have the ability to add to the table without adding the header again and keeping previous information. Here's my code:

import time as r
data = r.strftime("%d %m %Y %I %M")
with open('myfile.txt','a') as f:
    f.write(data + '\n')

Here's the output in the text file:

01 07 2022 01 19

Now here's the output I want:

_________________________________
|Day |Month |Year |Hour |Minute |
|-------------------------------|
|01  |07    |2022 |01   |19     |
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^|

And I want to have the ability that if I run the file again that it would add the new output it would look something like this:

_________________________________
|Day |Month |Year |Hour |Minute |
|-------------------------------|
|01  |07    |2022 |01   |19     |
|===============================|
|01  |07    |2022 |02   |10     |
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^|

I know this is an absurd post but does anyone know how? Thanks.


Solution

  • The first call to the fun function will create the header, add the first data and put the end line filled with '^'*31. To ensure, that it is indeed the first call and do not create the header anew at each subsequent call there is the if block.

    While the first call opens time.txt in the reading mode 'r', all other calls open it in the 'r+' mode which opens the file both for reading and writing. When the file is read and everything from it is saved to saved (everything, but for the end line), the cursor of the parser is moved the start of the opened file, so that it can be rewritten with the new data with the trailing end line.

    def fun():
        import time
        import os.path
        seperator='|'+'-'*31+'|\n'
        end = '|'+'^'*31+'|'
        if not os.path.isfile('time.txt'): #checking if the file exist
            with open('time.txt','w') as f:
                header= '_'*32+'\n'+\
                        '|Day |Month |Year |Hour |Minute |\n'
                t=time.localtime()
                data = (f'|{t[2]:<4}|{t[1]:<6}|{t[0]:<5}'
                        f'|{t[3]:<5}|{t[4]:<7}|\n')
                f.write(header+seperator+data+end)
        else:
            with open('time.txt','r+') as f:
                saved=f.readlines()[:-1] #saving all, but the end line
                f.seek(0) #set the cursor to the start of the file
                t=time.localtime()
                data = (f'|{t[2]:<4}|{t[1]:<6}|{t[0]:<5}'
                        f'|{t[3]:<5}|{t[4]:<7}|\n')
                f.writelines(saved+[seperator,data,end])            
    

    It may not be the ideal option that will meet your needs... And i dare not say that the code is faultlessly.

    Note: If the 'time.txt' already exists, but empty or/and without the header then the header won't be created.