[英]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 ',
我應該在行末位置也可以放在代碼的最后一行。
謝謝
您可以使用枚舉 :
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.