import os from datetime import datetime def write_log_file(s, fname): ''' Write s to fname, the most recent on the top''' curr_time = datetime.now().strftime('%Y-%m-%d %H:%M') print('Log at %s: %s' % (curr_time, s.strip())) content = '' if os.path.exists(fname): with open(fname) as f: content = f.read() with open(fname, 'w') as f: f.write('[' + curr_time + ']: ' + s.strip() + '\n' + content) if __name__ == '__main__': write_log_file('hello', 'testlog.txt'); write_log_file('logger', 'testlog.txt');