我正在寻找一种可以多次调用next()的方法,直到到达.csv文件中的特定行(基本上跳过所有内容,直到我想要的行为止),例如。
import csv
file = 'weatherfileexample.csv'
with open(file) as f:
reader = csv.reader(f)
headings = next(f) # I want this to be row 12 where Year;Month;Day;Hour;Minute;.... is located
.csv文件的内容如下所示。
LAT;;;;;47.0458;47.0458;47.0458;47.0458;47.0458;47.0458;47.0458 LON;;;;;21.9183;21.9183;21.9183;21.9183;21.9183;21.9183;21.9183 ASL;;;;;126.000;126.000;126.000;126.000;126.000;126.000;126.000 CITY;;;;;Oradea;Oradea;Oradea;Oradea;Oradea;Oradea;Oradea DOMAIN;;;;;NEMS4;NEMS4;NEMS4;NEMS4;NEMS4;NEMS4;NEMS4 LEVEL;;;;;2 m above gnd;10 m above gnd;10 m above gnd;2 m above gnd;2 m above gnd;10 m above gnd;10 m above gnd NAME;;;;;Temperature;Wind Speed;Wind Direction;Temperature;Temperature;Wind Speed;Wind Speed UNIT;;;;;°C;km/h;°;°C;°C;km/h;km/h AGGREGATION;;;;;daily mean;daily mean;daily mean;daily max;daily min;daily max;daily min UTC_OFFSET;;;;;2;2;2;2;2;2;2 Year;Month;Day;Hour;Minute;Temperature daily mean [2 m above gnd];Wind Speed daily mean [10 m above gnd];Wind Direction daily mean [10 m above gnd];Temperature daily max [2 m above gnd];Temperature daily min [2 m above gnd];Wind Speed daily max [10 m above gnd];Wind Speed daily min [10 m above gnd] 2019;12;14;00;00;6.74;13.75;170.60;11.32;3.43;21.14;2.60 2019;12;15;00;00;5.60;18.08;186.24;10.92;1.31;26.05;11.17
基本上我想要我的:
标题= .csv中突出显示的文本,然后从那里继续。
我知道我可以轻松地编辑.csv文件,但我想知道如何做。
我尝试过的事情
heading = next(f)* 12#12是我需要的数据所在的位置,它仅将firstrow乘以12次
也尝试过:
heading = next(f,12)#这只是游戏第一行。
非常感谢您!
P.S。 :Pastebin加载时出现问题,因此我无法在其中粘贴.csv。
答案 0 :(得分:1)
itertools.dropwhile将在满足给定条件时以可迭代方式跳过元素。将此功能与enumerate内置函数结合使用,仅在到达特定行后才可以处理行。
在此代码中,删除行的条件是enumerate
返回的行号小于11(enumerate
默认使用从零开始的计数)。
>>> import csv, itertools
>>> with open('weatherfileexample.csv', newline='') as f:
... reader = csv.reader(f, delimiter=';')
... # dropwhile returns the index from enumerate, which we can ignore, and
... # the row from csv.reader.
... for _, row in itertools.dropwhile(lambda x :x[0] < 11, enumerate(reader)):
... print(row)
...
['Year', 'Month', 'Day', 'Hour', 'Minute', 'Temperature daily mean [2 m above gnd]', 'Wind Speed daily mean [10 m above gnd]', 'Wind Direction daily mean [10 m above gnd]', 'Temperature daily max [2 m above gnd]', 'Temperature daily min [2 m above gnd]', 'Wind Speed daily max [10 m above gnd]', 'Wind Speed daily min [10 m above gnd]']
['2019', '12', '14', '00', '00', '6.74', '13.75', '170.60', '11.32', '3.43', '21.14', '2.60']
['2019', '12', '15', '00', '00', '5.60', '18.08', '186.24', '10.92', '1.31', '26.05', '11.17']
在平凡的情况下,使用dropwhile
过多,但在条件复杂和/或性能令人担忧的情况下可能有用。
答案 1 :(得分:0)
尝试:
[next(f) for i in range(12)]
headings = next(f)
或
data = list(f)
headings = data[12]
答案 2 :(得分:0)
您可以使用readlines()
:
with open(file) as f:
line = f.readlines()
line[12]
'2019;12;14;00;00;6.74;13.75;170.60;11.32;3.43;21.14;2.60\n'