python csv迭代;打印第1行和第2行,然后是第2行和第3行,依此类推

时间:2014-10-24 20:05:38

标签: python csv

我一直在努力奋斗数小时。我想打印第2行和第3行,创建一个新行,然后打印第3行和第4行+换行符,下一行第4行和第5行+ \ n ...实际上整个脚本做了更多的事情,但这是关键步骤我我在挣扎。

这是我的csv文件

ids,CLSZ_0.7,CLID_0.7
ZINC04474603,48,45
ZINC12496548,48,45
ZINC12495776,48,45
ZINC04546442,48,45
ZINC28631806,48,45

这是我的代码

ifile = 'bin_503_07.csv'

with open(ifile, 'rb') as f:
    object = csv.reader(f)
    object.next()  #skips first line
    for row in object:
        next_row = object.next()
        print row
        print next_row
        print "\n"

这就是我得到的结果(基本上是原始的.csv,但在2行之间插入换行符)。相反,我需要每一对新行从前一对的第二行开始。

['ZINC04474603', '48', '45']
['ZINC12496548', '48', '45']


['ZINC12495776', '48', '45']
['ZINC04546442', '48', '45']


['ZINC28631806', '48', '45']
['ZINC08860448', '48', '45']


['ZINC04655414', '48', '45']
['ZINC08860490', '48', '45']

任何帮助非常感谢

2 个答案:

答案 0 :(得分:1)

你可以这样做:

ifile = 'bin_503_07.csv'

with open(ifile, 'rb') as f:
    reader = csv.reader(f)
    reader.next()  #skips first line
    previous_row = reader.next()  # load first actual line
    for row in reader:   # this already calls "next()"
        print previous_row
        print row
        print   # no need to print "\n", empty "print" already does that
        previous_row = row  # "advance" by replacing previous with current

答案 1 :(得分:0)

import itertools

with open('path/to/file') as infile:
    a,b = tee(infile)
    next(b,None)
    for line1, line2 in zip(a,b):
        print line1.rstrip('\n')
        print line2.rstrip('\n')
        print ''