Created
May 15, 2010 00:46
-
-
Save endolith/401885 to your computer and use it in GitHub Desktop.
Log datestamped strings to a .csv file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| """ | |
| Event logger | |
| The basic idea is just to provide an interface dedicated to manual data | |
| logging. It will log the exact date and time that the user enters strings, | |
| and allow it to be formatted for output in various ways. | |
| Should be able to prompt the user to enter something at a given interval. | |
| endolith@gmail.com 2009-03-05 | |
| """ | |
| import os | |
| import csv | |
| from datetime import datetime | |
| def get_file_name(): | |
| '''Ask user for file name and make it valid''' | |
| # TODO: get log file name name from command line arguments | |
| print 'Enter name for log file or press <Enter> for datestamp' | |
| name = raw_input() | |
| if not name: | |
| name = 'Log ' + datetime.now().isoformat() | |
| # Sanitize for Windows - is there a standard function for this? | |
| name = name.replace(':','_') | |
| if not name.lower().endswith('.csv'): | |
| name += '.csv' | |
| return name | |
| def add_to_log(entry): | |
| '''Add an entry to both the memory log and CSV log''' | |
| log.append(entry) | |
| logWriter.writerow(entry) | |
| log_file.flush() | |
| # main: | |
| log_file_name = get_file_name() | |
| while os.path.exists(log_file_name): | |
| print '\nFile ' + log_file_name + ' already exists' | |
| log_file_name = get_file_name() | |
| # Both a list of lists in memory and a csv file on disk - maybe useful later? | |
| log_file = open(log_file_name, 'wb') | |
| logWriter = csv.writer(log_file) | |
| log = [] | |
| add_to_log(['Time', 'Event']) | |
| print '\nEnter log events followed by <Enter>' | |
| print 'Enter "end" when done\n' | |
| event = '' | |
| while event != 'end': | |
| print '>', | |
| event = raw_input() | |
| time_stamp = datetime.now() | |
| add_to_log([time_stamp, event]) | |
| #for timestamp, event in log: | |
| # print timestamp.isoformat() + ',' + event | |
| # print timestamp.strftime('%Y-%m-%d %H:%M:%S') + ',' + event | |
| log_file.close() | |
| print '\nData has been written to file ' + log_file.name | |
| # Stupid Windows closes the terminal after it executes | |
| print '\nPress Enter to close' | |
| raw_input() |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can also use AutoHotkey to press Tab and enter a timestamp every time you press the numpad Enter key, which may or may not be better.