I'm still new to Python and my codes are basically baby mutants! One thing I've been struggling with is editing a text file in such way: 1- Search for a specific string 2- If exists, replace it if not matching the expected. 3- If doesn't exist, add it the line before last.
After hours of banging my head to the wall I couldn't do it so I resorted just coming up with something that does the job for now which is the code you see below. Would anyone of you wizards show me the light to a more elegant solution? pretty please...
**Text:**
Sunset_settings {
inputs 3
lifetime 4
speed 24
xpos -415
ypos 949
focal_type edges
}
**Code:**
focal_type_v = 'points'
found = False
with open("4.txt", "r") as f:
lines = f.readlines()
for n in lines:
if "focal_type" in n:
found = True
if not found:
for index, line in enumerate(lines):
if line.startswith("ypos"):
break
lines.insert(index, " focal_type " + focal_type_v+ "\n")
with open("4.txt", "w") as f:
contents = f.writelines(lines)
if found:
fin = open("4.txt", "rt")
data = fin.read()
if 'focal_type faces' in data:
data = data.replace('focal_type faces', 'focal_type ' + focal_type_v)
elif 'focal_type points' in data:
data = data.replace('focal_type points', 'focal_type ' + focal_type_v)
elif 'focal_type edges' in data:
data = data.replace('focal_type edges', 'focal_type ' + focal_type_v)
elif 'focal_type bbox' in data:
data = data.replace('focal_type bbox', 'focal_type ' + focal_type_v)
else:
data = data.replace('selected true', 'focal_type ' + focal_type_v)
fin.close()
fin = open("4.txt", "wt")
fin.write(data)
fin.close()