Python line_num 打印行号只输出最后的行号
Python line_num printing the line number outputs only the last line number
我正在尝试打印 .csv 文件的行号,但它只输出所有行的最后一个行号,这是我的代码:
import csv
openfile = open('example_csv.csv')
readcsv = csv.reader(openfile, delimiter = ',')
list_csv_content = list(readcsv)
for row in list_csv_content:
print(f'Row #{readcsv.line_num} {row}')
输出是这样的:
Row #7 ['4/5/2015 13:34', 'Apples', '73']
Row #7 ['4/5/2015 3:41', 'Cherries', '85']
Row #7 ['4/6/2015 12:46', 'Pears', '14']
Row #7 ['4/8/2015 8:59', 'Oranges', '52']
Row #7 ['4/10/2015 2:07', 'Apples', '152']
Row #7 ['4/10/2015 18:10', 'Bananas', '23']
Row #7 ['4/10/2015 2:40', 'Strawberries', '98']
我做错了什么?
line_num
属性 只是您的 reader 阅读的总行数。
下面的代码应该可以工作,但是,您 enumerate
并获得实际的行,加上该行的 从零开始的 索引。
import csv
openfile = open('chart-images.csv')
readcsv = csv.reader(openfile, delimiter = ',')
list_csv_content = list(readcsv)
for line_num, row in enumerate(list_csv_content):
print(f'Row #{line_num} {row}')
- 已切换为枚举,如@vks所示
当您将 readcsv
保存到列表中时,您正在读取整个 csv,这就是 line_num 指向最后一行的原因。
您可以通过不将 csv 保存到列表中来解决:
openfile = open('test.csv')
readcsv = csv.reader(openfile, delimiter = ',')
for line in readcsv:
print(line, readcsv.line_num)
或通过枚举列表:
import csv
openfile = open('example_csv.csv')
readcsv = csv.reader(openfile, delimiter = ',')
list_csv_content = list(readcsv)
for i, row in enumerate(list_csv_content):
print(f'Row #{i} {row}')
我正在尝试打印 .csv 文件的行号,但它只输出所有行的最后一个行号,这是我的代码:
import csv
openfile = open('example_csv.csv')
readcsv = csv.reader(openfile, delimiter = ',')
list_csv_content = list(readcsv)
for row in list_csv_content:
print(f'Row #{readcsv.line_num} {row}')
输出是这样的:
Row #7 ['4/5/2015 13:34', 'Apples', '73']
Row #7 ['4/5/2015 3:41', 'Cherries', '85']
Row #7 ['4/6/2015 12:46', 'Pears', '14']
Row #7 ['4/8/2015 8:59', 'Oranges', '52']
Row #7 ['4/10/2015 2:07', 'Apples', '152']
Row #7 ['4/10/2015 18:10', 'Bananas', '23']
Row #7 ['4/10/2015 2:40', 'Strawberries', '98']
我做错了什么?
line_num
属性 只是您的 reader 阅读的总行数。
下面的代码应该可以工作,但是,您 enumerate
并获得实际的行,加上该行的 从零开始的 索引。
import csv
openfile = open('chart-images.csv')
readcsv = csv.reader(openfile, delimiter = ',')
list_csv_content = list(readcsv)
for line_num, row in enumerate(list_csv_content):
print(f'Row #{line_num} {row}')
- 已切换为枚举,如@vks所示
当您将 readcsv
保存到列表中时,您正在读取整个 csv,这就是 line_num 指向最后一行的原因。
您可以通过不将 csv 保存到列表中来解决:
openfile = open('test.csv')
readcsv = csv.reader(openfile, delimiter = ',')
for line in readcsv:
print(line, readcsv.line_num)
或通过枚举列表:
import csv
openfile = open('example_csv.csv')
readcsv = csv.reader(openfile, delimiter = ',')
list_csv_content = list(readcsv)
for i, row in enumerate(list_csv_content):
print(f'Row #{i} {row}')