I made this code for take some data from a .txt file. The text file is a large list of data from temperature with a format that is repetitive and have some lines at the beginning with the station reference. I took the first ten lines but only one time, then I jump to line 12 to take the headers and then I have a mark that tell me if a new year of records is beginning and jump to line 13 and write from the line 13 to 30.
Is there a Pythonic way, without a lot of next(f)
?
from itertools import islice
with open(rutaEscribir,'w') as w:
with open(rutaLeer) as f:
for line in islice(f,1,10):
w.write(line)
f.seek(0)
for line in islice(f,12,13):
w.write(line)
f.seek(0)
ano = 1977
for line in f:
sena = '&'
if sena in line:
print('Found')
print('Año: ',ano)
next(f)
next(f)
next(f)
next(f)
next(f)
next(f)
next(f)
next(f)
next(f)
next(f)
next(f)
next(f)
next(f)
for n in islice(f,0,31):
w.write(n)
ano += 1
Here is an excerpt from the file:
& I D E A M - INSTITUTO DE HIDROLOGIA, METEOROLOGIA Y ESTUDIOS AMBIENTALES
SISTEMA DE INFORMACION
VALORES TOTALES DIARIOS DE RECORRIDO DEL VIENTO (Kms) NACIONAL AMBIENTAL
FECHA DE PROCESO : 2016/09/08 ANO 1986 ESTACION : 26185020 MESOPOTAMIA
LATITUD 0553 N TIPO EST CO DEPTO ANTIOQUIA FECHA-INSTALACION 1970-JUN
LONGITUD 7519 W ENTIDAD 01 IDEAM MUNICIPIO LA UNION FECHA-SUSPENSION
ELEVACION 2314 m.s.n.m REGIONAL 01 ANTIOQUIA CORRIENTE BUEY
***********************************************************************************************************************************
DIA ENERO * FEBRE * MARZO * ABRIL * MAYO * JUNIO * JULIO * AGOST * SEPTI * OCTUB * NOVIE * DICIE *
***********************************************************************************************************************************
01 144 35 10 32 52 6 81 133 44 29 7 17
…
05 35 + 31 18 16 15 110 160 125 12 18 56
…
As you can see on the right, this is a repetitive file. In line 57 I put the &
marker for the start of a new year of records. The next few lines (57 to 65) contain the geographical position from the station, followed by the month header (ENERO,FEB...). Then, 31 lines contain the data for that year. I want to use PANDAS to analyze that data.
My code transforms it into something like this:
As you can see, the repetitive headers for geographical position and the months now appear just once.
But I think is possible to do it in a Pythonic way and not with a lot of next(f)
.