如何索引输出中的行

时间:2015-02-16 14:45:27

标签: python csv enumerate

我的CSV文件如下(两行以分号分隔的值)

01;John;231;this is row one
02;Paul;745;this is row two

我想要这样的结果:

01  ============== column 1 and row 1
John ============= Column 2 and row 1
231 ============== column 3 and row 1
this is row one ========column 4 and row 1

依此类推,直到csv文件结束。

直到现在我能够获取列位置但不能获取行。

def read_csv(csvfile):
    with open(csvfile, 'rb') as file:
        columns = 4
        reader = csv.reader(file, delimiter=';')
        for row in reader:
            for column in range(0, columns):
                 print row[column], ' ====== ', 'column ', column+1, ' and row ', 

我应该在代码的最后一行放置什么,我也可以有行位置。

由于

2 个答案:

答案 0 :(得分:3)

您可以使用enumerate

def read_csv(csvfile):
    with open(csvfile, 'rb') as file:
        columns = 4
        reader = csv.reader(file, delimiter=';')
        # i will count the rows, starting at 1
        for i, row in enumerate(reader, start=1):
            for column in range(0, columns):
                 print row[column], ' ====== ', 'column ', column+1, ' and row ', i

答案 1 :(得分:0)

您可以对两者使用enumerate并使用iterools.islice对每一行进行切片,根本不需要使用范围。

from itertools import islice  

with open(csvfile) as f:
    reader = csv.reader(f,delimiter=";")
    columns = 4
    for ind, row in enumerate(reader, 1):
        for ind2, column in enumerate(islice(row,columns), 1):
            print("{} ======== column {} and row {}".format(column,ind2, ind))


01 ======== column 1 and row 1
John ======== column 2 and row 1
231 ======== column 3 and row 1
this is row one ======== column 4 and row 1
02 ======== column 1 and row 2
Paul ======== column 2 and row 2
745 ======== column 3 and row 2
this is row two ======== column 4 and row 2

range默认情况下也从0开始,因此您只需使用range(columns),您也可以定期切片enumerate(row[:columns],1)