更改脚本以将值写入特定列

时间:2013-10-14 17:38:43

标签: python csv python-2.7 append rank

我编辑了以下脚本代码段来为我的数据集启用排名功能。现在,当我将其作为循环脚本的一部分运行时,它会将数据一遍又一遍地附加到csv的结束列。换句话说,csv只会累积列。

我不知道该怎么做,但我需要代码总是将数据输入到第17列。目前在第一次运行脚本时,csv包含16列但是在第二次运行时,csv包含25列,并且需要在第二次运行时覆盖第17列,而不是仅将结果附加到第26行。

使用的代码:

import csv
from itertools import count
from collections import defaultdict
from functools import partial

counts = defaultdict(partial(count, 1))  # create a new count starting at 1

# Read in the data
with open('../MODIFIED.csv', 'rb') as f:
    # if you have a header on the file
    # header = f.readline().strip().split(',')
    data = [line.strip().split(',') for line in f]

with open("../MODIFIED.csv", 'wb') as outfile:
    writer = csv.writer(outfile)
    for counter, row in enumerate(data):
        counter += 1
        if counter >=2:
            row[9] = next(counts[row[2]])  # get the next count value
        writer.writerow(row)

任何想法,帮助或建议都将不胜感激。如果需要,我可以提供更多细节和示例,我目前正在努力保持简洁。提前感谢SMNALLY

2 个答案:

答案 0 :(得分:1)

提交错误的代码肯定..

答案 1 :(得分:0)

我无法评论你的问题,这就是我在答案中发帖的原因,请添加更多信息和一些例子。以及为什么使用open函数使用csv.Dictreader() 它将每列作为dict,它也易于处理......