Keeping as much as possible your code structure, this should be the solution you are looking for. It’s meant to be easy to read and understand. However it is not the best solution, for that we need to know what selection looks like, or even better what your input file looks like.
def main():
with open('output.txt', 'w') as f:
for i in range(len(sections)):
date_row4 = sections[i].split("\n")[4].split(" ")
date_row5 = sections[i].split("\n")[5].split(" ")
print(date_row4)
print(date_row5)
month_row4 = date_row4[1]
year_row4 = date_row4[3]
month_row5 = date_row5[1]
year_row5 = date_row5[3]
if len(month_row4): # avoid to write empty lines in the output
f.write("{} {}{}".format(month_row4,year_row4,'\n'))
if len(month_row4):
f.write("{} {}{}".format(month_row5,year_row5,'\n'))
main()
2
solved Creating list with dates