GTXY20 wrote:
> Hi,
> 
> I have a CSV file as follows:
> 
> ID    Products
> 1     a b c d
> 1     a e
> 2     a b c
> 2     a
> 3     b c
> 3     a
> 4     d
> 5     a d
> 
> I am trying to write a script that will take the CSV file and output 
> another text file as follows:
> 
> ID   Products
> 1    a
> 1    b
> 1    c
> 1    d
> 1    a
> 1    e
> 
> etc.. for all of the ID's essentially I need to create a single instance 
> for products for each ID - currently the products are separated by a 
> space. I am thinking I need a for loop that will search on the space as 
> a delimiter...

I should probably be teaching you to fish but tonight I have extra fish :-)

If the products are single words then this is very simple. Something like

inp = open('input.txt')
out = open('output.txt')

# Headers
inp.next()
out.write('ID\tProducts\n')

for line in inp:
   fields = line.split()
   prodId = fields[0]
   products = fields[1:]
   for product in products:
     out.write('%s\t%s\n' % (prodId, product))

inp.close()
out.close()


If the product text is more complex then you might want to use the csv 
module to help read and write the file.

BTW in Python 3 you can write
   prodId, *products = fields.split()

http://www.python.org/dev/peps/pep-3132/

Kent
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to