【问题标题】:Adding(mathwise) rows of several csv files in python在python中添加(数学)几个csv文件的行
【发布时间】:2011-07-27 17:52:42
【问题描述】:

我有具有相同标题的 csv 文件(第一行和第一列包含所述标题)。其余单元格包含数字。我需要获取另一个 csv 文件并将两个 csv 文件中的数字相加。有没有办法用python中的csv函数做到这一点?

谢谢

【问题讨论】:

  • 我刚开始我还没有找到任何关于它的东西。我不知道 CSV 功能是否有效。我正在考虑将内容放入列表并添加它们,然后将其写回 csv 文件。

标签: python file function math csv


【解决方案1】:
import csv
f = csv.reader(open('filename1.csv', 'rb'))
g = csv.reader(open('filename2.csv', 'rb'))
output = csv.writer(open('ouputfile.csv', 'wb'))
for row_f in f:
    row_g = g.next()
    row_output = list()
    for argi, item in enumerate(row_f):
        try:
            row_output.append(int(item) + int(row_g[argi]))
        except ValueError, e:
            pass
    output.writerow(row_output)

这假设 file1 和 file2 具有相同的尺寸。您可以使用它来获得您想要的功能,但我认为这可能是一个不错的起点?

【讨论】:

  • 一切似乎都正常,但我将输出写入的 CSV 文件是空白的。有什么想法吗?
猜你喜欢
  • 2011-11-13
  • 2021-10-25
  • 2013-04-23
  • 2018-04-27
  • 2018-06-10
  • 2018-08-01
  • 2013-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多