Saturday, May 23, 2009

Writing time data to file

In the last post I wrote about a small command line utility for registering hours spent on different tasks. I never got to showing how to write to text files in Python, so let's get down to it now (what's better to do a Saturday evening than hacking away in Python?)!

First, to open a file for editing, you use the following syntax in Python:


where attribute is one of the following:
  • a - append: appends new text to the end of the file
  • w - write: write to file, will overwrite contents already there
  • r - read: does only give read access to the file
For our purpose we will use the append attrribute (a). What you create in this way is a file object, that has certain methods available to it depending on the attribute given to the constructor open. The one we will be using is, surprisingly enough, write:


When you create a file object, the entire file is loaded into your computers working memory (RAM). When you are done working on the file, you should close it to free memory and avoid unforeseen computer trolls to pop out and eat you. You do this by issueing the close method to your file object;


If you add the three code lines written here to the script outlined in the last post, you will have a working time registering tool!

No comments:

Post a Comment