【发布时间】: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])?