Hello. I am a complete newbit to Python. I am trying to read a text file (which is actually an svg file) and add a line to the text file. I would also like to remove certain text from the file. I am trying to edit some of the tags in the file. Here is the code that I have so far. I have only figured out how to read the file and append to it. But I don't know how to do actual edits.

def main():   
    f = open("F01.svg", "r")
    if f.mode == 'r':
        fl = f.readlines()
        for x in fl:
            if x.find("</g>") > -1:
                print (x)

if __name__ == "__main__":
  main()

This prints out the contents of the entire file. But now I need to find the </g> tag at the end and add another one either right before it or right after it. So I'm guessing I need a way to track all the </g> tags in the file and then after the last one add aonther one. I also think I need to know how I can also find a tag and add attributes to them.

thanks in advance.

Recommended Answers

All 2 Replies

Assuming you are taking the approach you have started with, I would recommend defining a functiont that seeks for the last example of a substring in a string:

def findLast(s, target):
    prev = 0
    pos = s.find(target, prev)
    while pos > -1:
        prev = pos
        pos = s.find(target, prev + len(target))
    return prev

However, as it happens, Python has a set of standard libraries for parsing XML-based markup, which SVG certainly is. While this may be more than you need right now, if you expect to be doing a lot more of this sort of thing, you might want to look into xml.etree.ElementTree or xml.parse.expat.

Thanks for your suggestion. I will look into that. I am very new to Python so this is very helpful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.