New file plus cut and paste fields

C

cam

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.

however, I've tried search for this in python but to no avil. anyone
can help? thanks! for example..in 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?
 
C

Christopher T King

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
is...
however, I've tried search for this in python but to no avil. anyone
can help? thanks! for example..in 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:
fields=line.split()

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:
fields=line.split()
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top