在Python中合并csv文件中的两行

时间:2014-07-21 09:25:30

标签: python csv

我是Python的新手,我正在尝试对csv文件中的每两行进行非常简单的合并。基本上我想这样:

输入:

[H1],1,2,3,4
[H2],5,6,7,8
[H1],a,b,c,d
[H2],e,f,g,h

输出:

[H1],1,2,3,4,[H2],5,6,7,8
[H1],a,b,c,d,[H2],e,f,g,h

这是一个简短的示例,但csv文件最多有167列,两行合并。这就是我所拥有的:

import csv
f = open("sample.csv",'rU').read().split("\n")
reader = csv.reader(f)
for row in reader:
    if row[0].startswith("[H1]"): 
        i=[]
        while i<167: n = row.append([",".join(row[i]+row[i+1])])
        print n

然而,当我运行它时,我收到以下错误:

    print n
NameError: name 'n' is not defined

感谢任何帮助,谢谢。

4 个答案:

答案 0 :(得分:1)

输入i.csv

1,2,3
foo,bar,baz
4,5,6
qux,quux.quuux

Python codce:

with open("i.csv") as f:
    reader = csv.reader(f)
    i = 0
    for row in reader:
        if i % 2 == 0:
            newRow = row
        else:
            newRow = newRow + row
            print(newRow)
        i = i + 1

输出:

['1', '2', '3', 'foo', 'bar', 'baz']
['4', '5', '6', 'qux', 'quux', 'quuux']

答案 1 :(得分:0)

while i<167: n = row.append([",".join(row[i]+row[i+1])])就像写作:

while i<167:
    n = row.append([",".join(row[i]+row[i+1])])

因此n的范围是循环块。您的print n超出了该范围,从而提升了NameError

您可以在n = None

之前添加while
n = None
while i<167: n = row.append([",".join(row[i]+row[i+1])])
print n

或者将print n移动到循环块中:

while i<167:
    n = row.append([",".join(row[i]+row[i+1])])
    print n

请注意,任何这些更改都会因超出范围错误而避免程序中断,但您会打印包含None的大量行,因为append会返回None:{{3 }}

答案 2 :(得分:0)

这是一种组合线对的方法:

import csv
from itertools import izip


def main():
    with open('sample.csv', 'rb') as input_file:
        reader = csv.reader(input_file)
        for even_row, odd_row in izip(reader, reader):
            combined_row = even_row + odd_row
            print combined_row


if __name__ == '__main__':
    main()

答案 3 :(得分:0)

import csv

f = open("sample.csv",'rU').read().split("\n")
reader = csv.reader(f)

i = 0

for row in reader:
    if i % 2 == 0:
        line = row
    else:
        line = line + row
        print ", ".join(line)

    i += 1