Mercurial > pylearn
changeset 420:040cb796f4e0
Removed feature of passing the file as a pathname from filetensor.{read, write}
Rationale:
1. The common pattern of multiple successive reads to load a list of arrays
doesn't work for the string argument.
2. It isn't clear without checking the docs whether the write() will open a file
in append mode, which could lead to bugs.
3. It's a fairly useless feature anyway, because the truly lazy programmer can
call write(open(filename, 'w'), mat) to reproduce the old behaviour if he
wants it, and without the open-mode ambiguity.
author | James Bergstra <bergstrj@iro.umontreal.ca> |
---|---|
date | Tue, 15 Jul 2008 12:57:21 -0400 |
parents | 43d9aa93934e |
children | e01f17be270a |
files | _test_filetensor.py filetensor.py |
diffstat | 2 files changed, 14 insertions(+), 11 deletions(-) [+] |
line wrap: on
line diff
--- a/_test_filetensor.py Mon Jul 14 16:48:02 2008 -0400 +++ b/_test_filetensor.py Tue Jul 15 12:57:21 2008 -0400 @@ -30,8 +30,12 @@ def test_filename(self): gen = numpy.random.rand(1) - write(self.fname, gen) - mat = read(self.fname, None, debug=False) #load from filename + f = file(self.fname, 'w') + write(f, gen) + f.close() + f = file(self.fname, 'r') + mat = read(f, None, debug=False) #load from filename + f.close() self.failUnless(gen.shape == mat.shape) self.failUnless(numpy.all(gen == mat))
--- a/filetensor.py Mon Jul 14 16:48:02 2008 -0400 +++ b/filetensor.py Tue Jul 15 12:57:21 2008 -0400 @@ -56,7 +56,8 @@ def read(f, subtensor=None, debug=False): """Load all or part of file 'f' into a numpy ndarray - If f is a string, it will be treated as a filename, and opened in read mode. + @param f: file from which to read + @type f: file-like object If subtensor is not None, it should be like the argument to numpy.ndarray.__getitem__. The following two expressions should return @@ -74,10 +75,6 @@ s_array = numpy.fromstring(s, dtype='int32') return s_array.item() - if isinstance(f, str): - if debug: print 'f', f - f = file(f, 'r') - #what is the data type of this matrix? #magic_s = f.read(4) #magic = numpy.fromstring(magic_s, dtype='int32') @@ -116,15 +113,17 @@ def write(f, mat): """Write a numpy.ndarray to file. - If 'f' is a string, then it will be interpreted as a filename. This filename - will be opened in 'w+' mode, and (automatically) closed at the end of the function. + @param f: file into which to write + @type f: file-like object + + @param mat: array to write to file + @type mat: numpy ndarray or compatible + """ def _write_int32(f, i): i_array = numpy.asarray(i, dtype='int32') if 0: print 'writing int32', i, i_array i_array.tofile(f) - if isinstance(f, str): - f = file(f, 'w+') try: _write_int32(f, _dtype_magic[str(mat.dtype)])