【问题标题】:How can i print columns in same rows with different 'codes' using csv python如何使用csv python在具有不同“代码”的同一行中打印列
【发布时间】:2014-04-08 07:07:58
【问题描述】:

这是我的 code.csv 文件:

one,two,three
1,2,3
2,3,4
3,4,5

和 code2.csv 文件:

,two,three
,2,3
,3,4
,4,5

这是我的 code.py 文件:

import csv

with open('code.csv', 'rb') as input, open('result.csv', 'wb') as output:
        reader = csv.DictReader(input)
        rows = [row for row in reader]
        writer = csv.writer(output, delimiter = ',')

        writer.writerow(["new_one", "new_two", "new_three"])

        for row in rows:
                if 'two' in row:
                        writer.writerow(['',row["two"]])

        for row in rows:
                if 'one' in row:
                        writer.writerow([row["one"]])

问题是输出打印在不同的行中:

new_one,new_two,new_three
,2
,3
,4
1
2
3

我该怎么做

for row in rows:
                    if 'one' in row:
                            writer.writerow([row["one"]])

这样打印

new_one,new_two,new_three
1,2
2,3
3,4

不必像这样输入

 for row in rows:
                if 'one' in row and 'two' in row:
                        writer.writerow([row["one"],row["two"]])

现在,如果我有 code2.csv 而不是 code.csv,后者 (if 'one' in row and 'two' in row:) 会给我错误“'one' not found”。所以我需要有类似“for row in rows[1]:”之类的东西。显然这不起作用,但类似的东西?

【问题讨论】:

  • 这是您要找的吗?对于行中的行: writer.writerow(row[:-1])?

标签: python csv row cell


【解决方案1】:

您必须逐行而不是逐列编写。我认为应该这样做:

    for row in rows:
        writer.writerow([row.get("one", ""), row.get("two", "")])

【讨论】:

  • 非常感谢。这行得通。我们为此奋斗了 3 天
猜你喜欢
  • 2023-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
相关资源
最近更新 更多