Pages

Tuesday, February 13, 2007

Python's Files

I was reading the following comment:


What I didn't like about Python was the fact that OOP seems bolted on. For example, to open a file you use "f = open("text.txt")" but to close it you do "f.close()". Ruby is much more elegant in that everything is an object.


and I thought I'd explain Python files a little just in case someone else makes the same mistake. (And by the way, everything in Python is an object, too.)

In Python, the "open()" function is actually an alias for the "file()" constructor. Yes, that's right -- what the commenter thought pointed out a non-object-oriented aspect of Python actually illustrates Python's object-oriented nature. So you create a file object 'f' using 'f = file("text.txt")', and you close it you do "f.close()".

No comments:

Post a Comment