I have this two files containing something like this for the first file
# 2018 2 21 4 13 53.7 -3.60886 139.51416 55.0 4.3 0.0 0.0 0.49
# 2018 3 25 6 4 37.0 -2.73768 140.02208 30.0 4.3 0.0 0.0 0.66
# 2018 4 1 7 36 30.7 -3.81268 139.93225 10.0 3.2 0.0 0.0 0.77
and this is the second one
sta phase time wt
GENI P 04:14:14.4 1.0
GENI S 04:14:29.9 1.0
SMPI P 04:14:22.6 1.0
SMPI S 04:14:44.7 1.0
ATNI P 04:17:30.1 1.0
SOEI P 04:17:39.4 1.0
ATNI mb 4.58 0.66
SOEI mb 4.56 1.37
sta phase time wt
GENI P 06:04:45.7 1.0
GENI S 06:04:49.5 1.0
JAY P 06:04:51.9 1.0
JAY S 06:05:01.6 1.0
ERPI P 06:05:33.4 1.0
FAKI P 06:06:26.9 0.0
SWI P 06:06:42.0 0.0
BSMI P 06:06:50.4 0.0
SAUI P 06:06:58.4 0.0
KRAI P 06:07:19.9 0.0
sta phase time wt
GENI P 07:36:52.4 1.0
GENI S 07:37:10.7 1.0
JAY P 07:36:58.3 1.0
JAY S 07:37:16.9 1.0
sta phase time wt
I wanted to combine this two file into one csv where I wanted to extract the content in between sta phase time wt and adding it under the event from the first file. One event is identified with # in from of the line and expecting result like this.
# 2018 2 21 4 13 53.7 -3.60886 139.51416 55.0 4.3 0.0 0.0 0.49
GENI P 04:14:14.4 1.0
GENI S 04:14:29.9 1.0
SMPI P 04:14:22.6 1.0
SMPI S 04:14:44.7 1.0
ATNI P 04:17:30.1 1.0
SOEI P 04:17:39.4 1.0
ATNI mb 4.58 0.66
SOEI mb 4.56 1.37
# 2018 3 25 6 4 37.0 -2.73768 140.02208 30.0 4.3 0.0 0.0 0.66
GENI P 06:04:45.7 1.0
GENI S 06:04:49.5 1.0
JAY P 06:04:51.9 1.0
JAY S 06:05:01.6 1.0
ERPI P 06:05:33.4 1.0
FAKI P 06:06:26.9 0.0
SWI P 06:06:42.0 0.0
BSMI P 06:06:50.4 0.0
SAUI P 06:06:58.4 0.0
KRAI P 06:07:19.9 0.0
# 2018 4 1 7 36 30.7 -3.81268 139.93225 10.0 3.2 0.0 0.0 0.77
GENI P 07:36:52.4 1.0
GENI S 07:37:10.7 1.0
JAY P 07:36:58.3 1.0
JAY S 07:37:16.9 1.0
I have tried extracting the content inside the sta phase time wt in but do not have any idea how to put it under the # from the first file
>Solution :
You can open your two files and loop over the data (file2). If the line starts with sta
then pick a new line from file1, else use the current line:
with (
open('file1.txt') as f1, # header file
open('file2.txt') as f2, # data file
open('out.txt', 'w') as out # output file
):
for line in f2:
if line.startswith('sta '):
# take a new header line, if none available use empty string
out.write(next(f1, ''))
else:
out.write(line)
out.txt
:
# 2018 2 21 4 13 53.7 -3.60886 139.51416 55.0 4.3 0.0 0.0 0.49
GENI P 04:14:14.4 1.0
GENI S 04:14:29.9 1.0
SMPI P 04:14:22.6 1.0
SMPI S 04:14:44.7 1.0
ATNI P 04:17:30.1 1.0
SOEI P 04:17:39.4 1.0
ATNI mb 4.58 0.66
SOEI mb 4.56 1.37
# 2018 3 25 6 4 37.0 -2.73768 140.02208 30.0 4.3 0.0 0.0 0.66
GENI P 06:04:45.7 1.0
GENI S 06:04:49.5 1.0
JAY P 06:04:51.9 1.0
JAY S 06:05:01.6 1.0
ERPI P 06:05:33.4 1.0
FAKI P 06:06:26.9 0.0
SWI P 06:06:42.0 0.0
BSMI P 06:06:50.4 0.0
SAUI P 06:06:58.4 0.0
KRAI P 06:07:19.9 0.0
# 2018 4 1 7 36 30.7 -3.81268 139.93225 10.0 3.2 0.0 0.0 0.77
GENI P 07:36:52.4 1.0
GENI S 07:37:10.7 1.0
JAY P 07:36:58.3 1.0
JAY S 07:37:16.9 1.0