如何将数据从csv文件中的列拆分为两个单独的输出csv文件?

时间:2013-08-25 09:50:43

标签: python csv

我有一个.csv文件,例如:

ID NAME CATEGORIES
1, x,   AB
2, xx,  AA
3, xxx, BA

如何根据类别形成两个输出.csv文件:

文件1:

ID NAME CATEGORY
1, x,   A
2, xx,  A
3, xxx, B

文件2:

ID NAME CATEGORY
1, x,   B
2, xx,  A
3, xxx, A

我设置了输入和输出,但只是一个空的for循环,我感到难过:

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()

我很感激任何帮助!

2 个答案:

答案 0 :(得分:0)

import csv

records = [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 = record
    new_record[-1] = "\t%s" % cat[0] # set category for file 1 with tab as a prefix
    outfileWriter1.writerow(new_record)
    new_record[-1] = "\t%s" % cat[1] # set category for file 2 with tab as a prefix
    outfileWriter2.writerow(new_record)

outfile1.close()
outfile2.close()

答案 1 :(得分:0)

import csv
with open('input.csv') as f, open('file1.csv', 'w') as f1, open('file2.csv', 'w') as f2:
    header = next(f)    #read header
    reader = csv.reader(f, delimiter=',', skipinitialspace=True) 
    f1.write(header)    #write header
    f2.write(header)    #write header
    writ1 = csv.writer(f1, delimiter=',') 
    writ2 = csv.writer(f2, delimiter=',')
    for row in reader:
        c1, c2 = row[-1]          #split the category into c1 and c2
        writ1.writerow(row[:-1] + [c1])  #write c1 to file1
        writ2.writerow(row[:-1] + [c2])  #write c2 to file2