Code Examples

Log data in text file

programming

This code sample in Python shows how to store some output string into a text file, with current date and time.

This function could be called inside some data processing, for monitoring purpose.

The text file is created in the root directory and opened in append mode.

# -*- coding: utf-8 -*-
"""
Created on Thu Jan 12 20:55:59 2023

@author: Konstantin
*****
This script creates a LoG file if it does not exist.
If exists, it will append the content inside.
"""

from datetime import datetime


def log_data(data):
    if len(data) == 0:
        return
    
    # get timestamp of last modification
    timestamp = datetime.now()

    # dd/mm/YY H:M:S
    strdate = timestamp.strftime("%d/%m/%Y %H:%M:%S")
    
    # create new file, or open existing in Append mode
    with open('log.txt','a') as f:
            # log data
            f.write(strdate)
            f.write("\n***Begin***\n") 
            f.write(data)
            f.write("\n***End***\n")    
            
#log_data("This is my data\nAnd one more line.")