I have got an input txt file formatted like this:
27/04/2023
00:00 0.1
06:00 0.5
23:00 0.9
28/04/2023
00:00 0.1
06:00 0.5
23:00 0.9
29/04/2023
00:00 0.1
06:00 0.5
23:00 0.9
The output should look like this:
27/04/2023 00:00 0.1
27/04/2023 06:00 0.5
27/04/2023 23:00 0.9
28/04/2023 00:00 0.1
28/04/2023 06:00 0.5
28/04/2023 23:00 0.9
29/04/2023 00:00 0.1
29/04/2023 06:00 0.5
29/04/2023 23:00 0.9
What is the most straigth forward and pythonic way to reformat the file?
What I am doing now:
- Read the file line by line.
- Check if line is a date and add its line number to a list and the date to another list
- From the line numbers list get pairs of consecutive date line numbers
- Slice the file content between concecutive date line numbers and insert the corresponding date.
The code is kind of clumpy. And it is not going to read and reformat the last day in the file...
from datetime import datetime
data_file = 'data.txt'
dates = []
dates_line_number = []
with open(data_file) as input_file:
for i, line in enumerate(input_file):
# read only the lines with dates, store their line number to list
# store the date to another list
try:
date_object = datetime.strptime(line.strip(), '%d/%m/%Y')
dates.append(date_object)
dates_line_number.append(i)
del date_object
except:
pass
file = open(data_file)
content = file.readlines()
i = 0
f = open("outfile.txt", "w")
for index in range(len(dates_line_number)):
# get pairs of consecutive date line numbers
ls_index = dates_line_number[index:index+2]
if len(ls_index) == 2:
start = ls_index[0]+1
end = ls_index[1]-1
# slice the file content between concecutive date line numbers
ls_out = (content[start:end+1])
# insert corresponding date string
str_date = f"{dates[i].strftime('%d/%m/%Y')} "
ls_out.insert(0, '')
str_out = str_date.join(ls_out)
f.write(str_out)
i = i+1
f.close()