xiaozai
Posts: 13
Joined: Fri Sep 02, 2016 7:27 am

Append text to text file with timestamp

Thu Nov 10, 2016 10:26 am

I want to append the output from a python code into a text file. Above is my python code and i loop it for every 2 hour

Code: Select all

if response == 0:
    print(hostname, "is up")

    if option == 1:
       print(option, "is the option')
       print('this is option number 1')
    elif option == 2:
       print(option, "is the option')
       print('this is option number 2')
    else:
       print(option, "is the other option')
       print('this is the result of other option')
i notice that i need the following code to append the result to a text file.

Code: Select all

with open("test.txt", "a") as myfile:
    myfile.write("appended text")
How can i record every output to a text file and include time stamp to it? for example

Code: Select all

09:10  192.168.0.1 is up
09:10  1 is the option
09:11   this is option number 1
11:15  192.168.0.1 is up
11:10  1 is the option
11:11   this is option number 1
13:10  192.168.0.1 is up
13:10  3 is the other option
13:11   this is the result of other option

scotty101
Posts: 3531
Joined: Fri Jun 08, 2012 6:03 pm

Re: Append text to text file with timestamp

Thu Nov 10, 2016 11:52 am

This seems like it would be a good candidate for the built in python logging module rather than spinning your own version using print or writing to a file.

https://docs.python.org/3/howto/logging.html

You can modify the format of the log to display a time stamp before each entry.
Last edited by scotty101 on Thu Nov 10, 2016 11:56 am, edited 1 time in total.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

scotty101
Posts: 3531
Joined: Fri Jun 08, 2012 6:03 pm

Re: Append text to text file with timestamp

Thu Nov 10, 2016 11:55 am

Here is a very basic example of setting up the logger and setting the format with a time/date stamp

Code: Select all

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG, format='%(asctime)s %(message)s')
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Return to “Python”