[Tutor] after string.split()

ibraheem umaru-mohammed ium@micromuse.com
Thu, 10 May 2001 18:51:45 +0100


[Rob Andrews wrote...]
<snip>
-| a few points. This is how I initially tackle the file:
-| 
-| >>> for line in fileinput.input("mangleme.txt"):
-| 	words = string.split(line, ",")
-| 
-| And this is an abbreviated version of file contents:
-| 
-| "Primary Key","Name","Company","Address1","Address2","City","State","Zip"
-| 1,"John Q. Public","ACME Widgets","P.O. Box 12345",,"Auburn","AL","36831"
-| 
-| I need to remove the Primary Key field, for instance, while leaving the rest
-| of the file's contents intact. Can anyone recommend resources where I can
-| find out what I can do to the split "parts"?
-| 

Well, since no-one seems to have replied, here is my attempt:

--- cut here ---

#!/usr/bin/env python

import fileinput
import string
import sys

def process(line):
	line=string.join(string.split(line,",")[1:],",")
	sys.stdout.write(line)

for line in fileinput.input(sys.argv[1:], inplace=1, backup='.old'):
	process(line)

--- cut here ---

You can then use this as follows:

	$./remove_first_field.py file1 file2

And this should leave you with a backup of the original file (.old).

Hope that helps,

Kindest regards,

	--ibs.

-- 
Sometimes you get an almost irresistible urge to go on living.