Sunday, February 17, 2008

Twisted's filepath Module

Glyph recently blogged about some of the buried treasure in Twisted, the filepath module in particular. Since working at Divmod, I've made use of this module quite a bit, and thought I'd share some of the features that I've found most useful (and intuitively nice to use).

Assuming you've got Twisted installed, let's fire up a python interpreter and import the FilePath class and instantiate it with /tmp and test some basic operations:

Isn't that nice? I love not having to import and use the os.path.exists function; it's a method on the object representing a file or a path, as it should be. I also enjoy the convenience FilePath offers when it comes to creating paths:

We had to call restat() so that the object would check the file system again (since we just made some changes). Now, for some files:

And if you don't believe that, we can switch to shell:

Reading and writing operations are the same as usual:

But you can use shortcuts like this, too:

Let's get the path and recheck the file size, just to make sure:

Or, again from shell:

Hmm... for some reason, I really like this file and want to keep it. What do I do?

That's it! Nice, eh? Of course, we're careful, so we check to make sure it happened:

To see more, check out the source, or at least do dir(FilePath) to see what other goodies this class has to offer, and enjoy :-)

Technorati Tags: , ,

No comments: