generic text read function
John Hunter
jdhunter at ace.bsd.uchicago.edu
Thu Mar 17 22:25:34 EST 2005
>>>>> "les" == les ander <les_ander at yahoo.com> writes:
les> Hi, matlab has a useful function called "textread" which I am
les> trying to reproduce in python.
les> two inputs: filename, format (%s for string, %d for integers,
les> etc and arbitary delimiters)
les> variable number of outputs (to correspond to the format given
les> as input);
les> So suppose your file looked like this str1 5 2.12 str1 3 0.11
les> etc with tab delimited columns. then you would call it as
les> c1,c2,c3=textread(filename, '%s\t%d\t%f')
les> Unfortunately I do not know how to read a line from a file
les> using the line format given as above. Any help would be much
les> appreciated les
Not an answer to your question, but I use a different approach to
solve this problem. Here is a simple example
converters = (str, int, float)
results = []
for line in file(filename):
line = line.strip()
if not len(line): continue # skip blank lines
values = line.split('\t')
if len(values) != len(converters):
raise ValueError('Illegal line')
results.append([func(val) for func, val in zip(converters, values)])
c1, c2, c3 = zip(*results)
If you really need to emulate the matlab command, perhaps this example
will give you an idea about how to get started. Eg, set up a dict
mapping format strings to converter functions
d = {'%s' : str,
'%d' : int,
'%f' : float,
}
and then parse the format string to set up your converters and split function.
If you succeed in implementing this function, please consider sending
it to me as a contribution to matplotlib -- http://matplotlib.sf.net
Cheers,
JDH
More information about the Python-list
mailing list