如何在我的输出中索引行

How to index rows in my output

我的 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 ', 

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

谢谢

您可以使用 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

您可以对两者都使用 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)