python-scripts/logoff-log.py
2022-10-02 12:43:53 +02:00

71 lines
2.0 KiB
Python

import os
from datetime import date
from datetime import datetime
# Set the location of the file to write to, in the user Documents directory
logfile = os.path.join(os.path.join(os.environ['USERPROFILE']),
r'Documents\logoff.log')
# Create the file if it does not exist yet
if not os.path.exists(logfile):
with open(logfile, 'w'):
pass
# Determine the current date and time
today = date.today()
now = datetime.now()
current_day = today.strftime("%d.%m.%Y")
# print("Today's date:", current_day)
current_time = now.strftime("%H:%M:%S")
# print("Current Time =", current_time)
# Class for prepending the date and time to the log file
class Prepender(object):
def __init__(self,
file_path,
):
# Read in the existing file, so we can write it back later
with open(file_path, mode='r') as f:
self.__write_queue = f.readlines()
self.__open_file = open(file_path, mode='w')
def write_line(self, line):
self.__write_queue.insert(0,
"%s\n" % line,
)
def write_lines(self, lines):
lines.reverse()
for line in lines:
self.write_line(line)
def close(self):
self.__exit__(None, None, None)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if self.__write_queue:
self.__open_file.writelines(self.__write_queue)
self.__open_file.close()
# Prepend the determined date and time to the top of the log file
with Prepender(logfile) as f:
# Must write individual lines in reverse order
f.write_line(current_day+' - '+current_time)
# with Prepender(logfile) as f:
# Or, use write_lines instead - that maintains order.
# f.write_lines(
# ['This will be line 1',
# 'This will be line 2',
# 'This will be line 3',
# ]
# )