Hello, this post is half a question, half a proposal. Q: what happens to the filesystem file, and to the python file object below? text = file(fn).read() (used 'file' instead of 'open' in purpose) Note that there seemingly is no way to close or del the file object, nor even to check its 'closed' flag. I would expect that, in the case a file remains unnnamed, it is automatically closed and del-ed. If not, do you think it is sensible to ensure that? In this case, we have a both safe and compact idiom to read file content. I consider this good, because the concept of "read file content" is both a single and simple operation -- and rather common. Else, I would propose a pair of string methods (rather than 2 more builtin funcs) .filetext() & .filebytes(). In both cases, the target string is (supposed to be) a filename. Below an example. =================== class FString(str): ''' custom string implementing file content reading ''' TEXT_MODE = 'r' BYTES_MODE = 'rb' NO_FILE_MESSAGE = 'Cannot open file "%s".' def filetext(self): return self._filecontent(FString.TEXT_MODE) def filebytes(self): return self._filecontent(FString.BYTES_MODE) def _filecontent(self, mode): try: f = open(self, mode) except IOError,e: raise ValueError(FString.NO_FILE_MESSAGE % self) bytes = f.read() f.close() return bytes ===================
from FString import FString fn = FString("test.txt") fn.filetext() 'foo\nbar\n' fn.filebytes() 'foo\nbar\n' fn = FString("fool.txt") fn.filetext() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "FString.py", line 12, in filetext raise ValueError(NO_FILE_MESSAGE % fn) ValueError: Cannot open file "fool.txt". ===================
I take the opportunity to ask whether there is a chance in the future to be able to customize builtin types. (In this case many proposals on this list will simply vanish.) Denis ------ la vita e estrany
participants (5)
-
Chris Rebert
-
Josiah Carlson
-
R. David Murray
-
Scott David Daniels
-
spir