Tuesday, September 05, 2006

» ruby reopen +

In ruby we have a nifty reopen method we can use on references to file-handles that are already opened. This is helpful when you need to open a file as read-only, then you want to write to the same file, or you just want to use the same reference to point to a new file-handle. You simply reopen and go on about your merry way. Usually this is used within a File.open block. But with python you have to explicitly close the original file-handle and open a new one. So here is a convenience class-wrapper/method to emulate the ruby functionality:

class file(file):
def reopen(self, name=None, mode='w', bufsize=None):
if not name:
name = self.name
if not self.closed:
self.close()
if bufsize:
self.__init__(name, mode, bufsize)
else:
self.__init__(name, mode)
return self

fh = file('test.txt', 'rb')
print fh # <open file 'test.txt', mode 'rb' at 0xb7c92814>
fh.reopen(mode='wb')
print fh # <open file 'test.txt', mode 'wb' at 0xb7c92814>
fh.close()

This way we can reopen a different file, or the same file in a different mode, just as with ruby, and the custom method will take care of closing the existing file-handle, opening the new one, and keeping the same reference.

2 Comments:

Blogger Evan Fosmark said...

This comment has been removed by the author.
June 18, 2008 at 3:22 AM

 
Blogger MonkeeSage said...

Not sure what you mean. If I try the following in python:

fh = file('text1.txt', 'rb')
print fh
fh.close()
fh = file('text2.txt', 'wb')
print fh
fh.close()

I get:

<open file 'text1.txt', mode 'rb' at 0xb7be7610>
<open file 'text2.txt', mode 'wb' at 0xb7be76b0>

I.e., a different file handle is allocated for each open() call. This is different from what ruby does with the reopen method. My python code adds a reopen method to python that reuses the same file handle, like ruby.
November 8, 2008 at 7:42 PM

 

Post a Comment

<< Home