I have a .csv file, e.g.:
ID NAME CATEGORIES
1, x, AB
2, xx, AA
3, xxx, BA
How would I get this to form two output .csv files based on the category e.g.:
File 1:
ID NAME CATEGORY
1, x, A
2, xx, A
3, xxx, B
File 2:
ID NAME CATEGORY
1, x, B
2, xx, A
3, xxx, A
I have the input and output set up, but just an empty for loop where I'm stumped:
records = [line for line in csv.reader(open('test_input.csv', 'rt'), delimiter=',')]
outfile = open('test_output1.csv', 'wt')
outfileWriter = csv.writer(outfile, delimiter=',')for record in records:#something!outfileWriter.writerow(record)outfile.close()
I'd appreciate any help!
import csvrecords = [line for line in csv.reader(open('test_input.csv', 'rt'), delimiter=',')]
outfile1 = open('test_output1.csv', 'wt')
outfile2 = open('test_output2.csv', 'wt')
outfileWriter1 = csv.writer(outfile1, delimiter=',')
outfileWriter2 = csv.writer(outfile2, delimiter=',')# headers always the same
outfileWriter1.writerow(records[0])
outfileWriter2.writerow(records[0])for record in records[1:]:cat = record[-1].strip() # get category in form "AB"new_record = recordnew_record[-1] = "\t%s" % cat[0] # set category for file 1 with tab as a prefixoutfileWriter1.writerow(new_record)new_record[-1] = "\t%s" % cat[1] # set category for file 2 with tab as a prefixoutfileWriter2.writerow(new_record)outfile1.close()
outfile2.close()