New file plus cut and paste fields

Christopher T King squirrel at WPI.EDU
Fri Jul 9 15:31:30 CEST 2004

On 8 Jul 2004, cam wrote:

> Does python support text field editing like the awk command? in awk,
> we're allow to extract a certain field and output it to another file.

Not as an implicit part of the language like Awk, but what you can do 

> however, I've tried search for this in python but to no avil. anyone
> can help? thanks! for python..I have this..
> <Hello Where Are>
> Ok, I wanna put the <hello> in one new file, then the word <Where> in
> another new file and finally, <Are> in the 3rd file. Is this possible
> in python?

Use str.split() to split a line up:

for line in inputfile:

You can then access the individual fields as fields[0], fields[1], etc. 
Use either str.join() or a print command (probably easier) to concatenate 
them back together:

for line in inputfile:
    print >>outputfile, fields[1], fields[2], fields[0]

The above code is equivalent to the awk script '{ print $2 " " $3 " " $1 }' 
(dunno if that's good awk style or not), providing you've previously 
opened inputfile and outputfile.

If you want to parse more complex text files, try the csv module - it will 
take care of irregularities in CSV files for you.

More information about the Python-list mailing list