thoughts = rand()

Wednesday, February 6, 2008

Python aha moment #1 - cruising through a text file

I am planning to write a series of blogs documenting all my "aha" moments with Python. The "aha" moments are those times at which I come across some piece of Python code and murmur to myself - "Python seems to be really cool!"

So here is my first aha moment - cruising through a text file:

for line in file("C:\\Windows\\System32\\drivers\\etc\\hosts"):
     print line

The above lines of Python code will:

a) open the 'hosts' file
b) print every line of that file to the console, and
c) close the file after all the lines are read.

This is a really productive way of parsing text files!

No comments: