尝试跳过数据文件的i行(然后处理j行)。关于csv文件长度的大量答案。 count或.line_num没有成功。
如何在csv.reader中访问当前行号?
import csv
def csv_reader(df):
i = 90
with open(df, 'r') as csvfile:
for line in range(0, i):
next(csvfile)
for line in csv.reader(csvfile, delimiter=' ', skipinitialspace = True):
print(csv.reader.line_num) # Invalid line
示例数据:
Last Quarter
Visit Astronomy
Daily Weather History & Observations
2018 Temp. (°C) Dew Point (°C) Humidity (%) Sea Level Press. (hPa) Visibility (km) Wind (km/h) Precip. (mm) Events
Mar high avg low high avg low high avg low high avg low high avg low high avg high sum
1 27 19 12 13 9 4 82 49 21 1016 1012 1007 10 10 10 24 11 - 0.00
2 25 20 14 14 12 9 82 61 32 1017 1014 1010 10 10 10 21 10 - 0.00
3 31 22 14 15 13 7 94 59 13 1014 1011 1007 10 10 10 27 8 - 0.00
4 30 21 13 15 13 6 82 59 13 1016 1012 1009 10 10 10 34 11 - 0.00
5 24 19 15 16 13 11 82 71 46 1022 1016 1013 10 10 10 35 13 - 0.00 Rain
6 20 14 9 12 9 6 82 60 31 1028 1024 1021 10 10 10 32 19 47 0.00
7 23 16 9 13 10 7 100 71 29 1029 1027 1024 10 10 5 29 11 37 0.00 Rain
Other random data follows
答案 0 :(得分:1)
您可以使用for index, line in enumerate(csv.reader(csvfile, delimiter=' ', skipinitialspace = True)):
print('Index %s' % str(index + 1)) # enumerate starts with 0
访问行号。
{{1}}