python 分类相同数据放入相同文档里解决思路

python 分类相同数据放入相同文档里
数据如下
4, 8, 1.3, 0.3, 3, ca, 45.76
4, 8, 1.7, 0.3, 3, ab, 49.9
4, 8, 1.9, 0.3, 2, aa, 44.06
4, 8, 2.1, 0.3, 2, aa, 44.06
4, 9, 0.3, 0.3, 3, ca, 43.07
4, 9, 1.7, 0.3, 3, acd, 49.04
4, 9, 1.7, 0.3, 3, cb, 49.04
4, 9, 1.9, 0.3, 2, cb, 47.44
4, 9, 2.1, 0.3, 2, cb, 47.44
4, 10, 0.3, 0.3, 7, ab, 32.65
4, 10, 0.3, 0.3, 7, ca, 32.65
现在我要根据第6列把相同的一列数据放入相同的txt里,比如所有aa的数据放入aa.txt里,ab数据放入ab.txt里,但现在我写的只保存了最后一次写入的数据,好像是把前面的都覆盖了,请大家帮帮忙,如果能解释下最好了
import re

infile = open ('D:/1.txt', 'r')
for row in infile.readlines():
  #print row
  row = row.strip()
  parts = row.split(',')
  #print parts[5]
  outfile = open ('D:/%s.txt' % (parts[5]), 'w')
  outfile.write(row + '\n')
infile.close()
outfile.close()


------解决方案--------------------
对。 下面代码没测试过!

Python code

result = {}
for line in open(input, 'r'):
  key = line.split(',')[5].strip()
  if key in result:
    result[key].append(line)
  else:
    result[key] = [line]
for key, data in result.items():
  output = open(key+".txt", 'w')
  output.write('\n'.join(data))
  output.close()

------解决方案--------------------
sry上面outfile =那行也是重复打开文件不对,改下用if语句:
if parts[5] not in outfiledict:
outfiledict[parts[5]] = open('D:/%s.txt' % parts[5], 'w')
outfile = outfiledict[parts[5]]