本文介绍了如何将数据从csv文件中的列分成两个单独的输出csv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个.csv档案,例如: ID NAME CATEGORIES 1,x,AB 2,xx,AA 3,xxx,BA 以基于类别形成两个输出.csv文件例如: 文件1: code> ID NAME CATEGORY 1,x,A 2,xx,A 3,xxx,B 文件2: ID名称类别 1, x,B 2,xx,A 3,xxx,A 我有输入和输出设置,但只是一个空的for循环,我被困住: records = line in csv.reader(open('test_input.csv','rt'),delimiter =',')] outfile = open('test_output1.csv','wt') outfileWriter = csv.writer(outfile,delimiter =',') 记录在记录中: #something! outfileWriter.writerow(record) outfile.close() $ import csv $ b $ b records = [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分隔符=',') #头部总是相同 outfileWriter1.writerow(records [0]) outfileWriter2.writerow(records [0]) 在记录中记录[1:]: cat = record [-1] .strip()#以AB形式获取类别 new_record = record new_record [-1 ] =\t%s%cat [0]#设置文件1类别,以tab作为前缀 outfileWriter1.writerow(new_record) new_record [-1] =\t% s%cat [1]#设置文件2的类别,以tab作为前缀 outfileWriter2.writerow(new_record) outfile1.close() outfile2.close I have a .csv file, e.g.:ID NAME CATEGORIES1, x, AB2, xx, AA3, xxx, BAHow would I get this to form two output .csv files based on the category e.g.:File 1:ID NAME CATEGORY1, x, A2, xx, A3, xxx, BFile 2:ID NAME CATEGORY1, x, B2, xx, A3, xxx, AI 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 sameoutfileWriter1.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() 这篇关于如何将数据从csv文件中的列分成两个单独的输出csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-14 11:30