I am trying to manually input a Carmodel and when this is found within that defined region to look for another subregion named 'Date' within the first region and after it to add the line with the following string "For rent". Something like this (Please see below the expected output highlighted with #, within example.txt)
#Region1 starts here
Carname
"Ford Ranger"
Color "Red"
Mileage "1024"
#Subregion1 starts here
Date
11/02/2018
/
#Subregion1 ends here
#Region1 ends here
#Add line here "For rent"
#Region2 starts here
Carname
"Toyota Prius"
Color "Red"
Mileage "1024"
#Subregion2 starts here
Date
10/06/2019
/
#Subregion2 ends here
#Region2 ends here
#Add line here "For rent"
This list continues for hundreds of entries in the .txt file, every Carname respresent a new Region with its own subregion.
But it should target just 1 at a time as it should look for manual user input. For the above example the manual input would be:"Ford Ranger"
This is what I've tried but I got stuck:
transitions = dict()
in_region = False
reg_end = -1
current_title = None
carmodel = input("input carmodel:")
with open("example.txt","r") as testfile:
content = testfile.readlines()
for idx, line in enumerate(content):
if line.startswith('Carname'):
#if line.startswith ('Date') within the input 'Carmodel'
#if line.endswith ('/') within the Date region
# Commit last transition before this to dict, if any
if current_title:
transitions[reg_end] = current_title
# add suffix for printing
current_title = 'For rent\n'
elif line.strip().startswith(carmodel):
in_region = True
# This will be overwritten while we remain in the region
reg_end = idx
elif in_region:
in_region = False
if current_title:
transitions[reg_end] = current_title
with open("example.txt", "w") as output:
for idx, line in enumerate(content):
output.write(line)
if idx in transitions:
output.write(transitions[idx])
This is more of a followup of this: Crosspost
Any help would be appreciated. Thanks!