simplified interface:

name == None: read from stdin
outname == None and not readonly mode: do in-place substitution of name (with transparent file renaming upon table.close)
This commit is contained in:
Philip Eisenlohr 2015-08-12 17:42:38 +00:00
parent f9348398ce
commit 64515d7aca
1 changed files with 14 additions and 10 deletions

View File

@ -16,14 +16,15 @@ class ASCIItable():
'data', 'data',
] ]
tmpext = '_tmp' # filename extension for in-place access
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def __init__(self, def __init__(self,
name = 'STDIN', name = None,
outname = None, outname = None,
buffered = False, # flush writes buffered = False, # flush writes
labeled = True, # assume table has labels labeled = True, # assume table has labels
readonly = False, # no reading from file readonly = False, # no reading from file
writeonly = False, # no writing to file
): ):
self.__IO__ = {'output': [], self.__IO__ = {'output': [],
'buffered': buffered, 'buffered': buffered,
@ -33,17 +34,19 @@ class ASCIItable():
'dataStart': 0, 'dataStart': 0,
} }
self.__IO__ .update({'in': sys.stdin, self.__IO__['inPlace'] = not outname and name and not readonly
'out': sys.stdout, if self.__IO__['inPlace']: outname = name+tmpext # transparently create tmp file
} if name == 'STDIN' else self.__IO__['in'] = (open( name,'r') if os.access( name, os.R_OK) else None) if name else sys.stdin
{'in': sys.stdin if writeonly else open(name,'r') , self.__IO__['out'] = (open(outname,'w') if not os.path.isfile(outname) \
'out': sys.stdout if readonly else open(outname,'w'), or os.access(outname, os.W_OK) else None) if outname else sys.stdout
}
)
self.info = [] self.info = []
self.labels = [] self.labels = []
self.data = [] self.data = []
if self.__IO__['in'] == None \
or self.__IO__['out'] == None: raise IOError # complain if any required file access not possible
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def _transliterateToFloat(self, def _transliterateToFloat(self,
x): x):
@ -113,6 +116,7 @@ class ASCIItable():
except: except:
pass pass
if dismiss and os.path.isfile(self.__IO__['out'].name): os.remove(self.__IO__['out'].name) if dismiss and os.path.isfile(self.__IO__['out'].name): os.remove(self.__IO__['out'].name)
if self.__IO__['inPlace']: os.rename(self.__IO__['out'].name, self.__IO__['out'].name[:-len(tmpext)])
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def head_read(self): def head_read(self):
@ -516,4 +520,4 @@ class ASCIItable():
microstructure[i:i+s] = items[:s] microstructure[i:i+s] = items[:s]
i += s i += s
return microstructure return microstructure