[Tutor] Parsing text file?

Karl Pflästerer sigurd at 12move.de
Thu Apr 15 15:31:49 EDT 2004

On 15 Apr 2004, Kooser, Ara S <- askoose at sandia.gov wrote:

> file. I now need to remove the first column of data and then convert the
> second. Is parsing right for this? Are there good websites for me to read or
> books on this? I am trying to write as much of my own code as possible and
> ask questions. ;)  Thanks. This is on Python 2.3.3. 

> My data files looks like this:
> 16
> 1  1  0.00000  0.68337  0.25020
> 2  2  0.00000  0.29020  0.25020
> 3  3  0.00000  0.08104  0.25020
> 4  4  0.00000  0.00000  0.25020
> Etc...

Is `16' in the first line part of your file?  Your task could be solved
pretty straightly: read each line of the file, split it on
whitespace, convert the second column and write the data in a new file.
(no need for a lot of books here).

If you used a generator function you could write it like that:

def proc_file (f, cfun=lambda n: n):
    for line in f:
        line = line.split()[1:]
        line[0] = cfun(line[0])
        yield ' '.join(line) + '\n'

inf = file('INFILE')
out = file('OUTFILE', 'w')
out.writelines(proc_file(inf, convfun))

`convfun' must be the function to convert your data (if you don't use a
second argument the identity function gets used).

If `16' is part of your data you must treat the first line specific.

Please do *not* send copies of replies to me.
I read the list

More information about the Tutor mailing list