0

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()
  • 1
    Write elegant code takes time, but be proud of yours, it's works! As a sugestion, give you a time to explore similar opensource codes, also you could read things like the [zen of python](https://www.python.org/dev/peps/pep-0020/) – Tané Jul 14 '21 at 19:29
  • your current question format is a little confusing........try like this........... give your original text........ give the expected text............. and list the changes required to convert the original text to expected text. – Joshua Jul 14 '21 at 19:38
  • thank you guys! It does indeed take time. – Sam Salek Jul 16 '21 at 07:03

0 Answers0