【问题标题】:Changing script to write values to specific column更改脚本以将值写入特定列
【发布时间】:2013-10-22 08:29:45
【问题描述】:

我编辑了以下脚本 sn-p 来为我的数据集完成排名函数。现在,当我让它作为循环脚本的一部分运行时,它会一遍又一遍地将数据附加到 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)

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

【问题讨论】:

    标签: python csv python-2.7 append rank


    【解决方案1】:

    确定提交了错误的代码..

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2011-11-06
        • 1970-01-01
        • 2014-03-08
        • 2022-12-02
        • 1970-01-01
        • 1970-01-01
        • 2020-01-14
        • 2023-01-08
        • 1970-01-01
        相关资源
        最近更新 更多