使用默认dict-valu在python中修改CSV中的列

2024-04-19 17:54:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个几乎有10000行的CSV文件。我用默认的dict保存了完整的数据

import csv
from collections import defaultdict


columns = defaultdict(list) 

testfile = open('test.txt' , 'a+')
with open('test.csv') as f:
    reader = csv.DictReader(f) 
    for row in reader: 
        for (k,v) in row.items(): 
            columns[k].append(v) 


print  >>  testfile ,"\n".join(columns['A'])
print  >>  testfile ,"\n".join(columns['B'])

现在我根据一些比较修改列['A']和列['B']。在

^{pr2}$

这给了我修改后的column['A']。在

现在我想把这个修改过的列写到同一个CSV中。但是writerow()方法正在将所有内容添加到文件第一列的末尾。在


Tags: columns文件csvintestimportforopen