2022-01-26

Adding quotes to text in line using Python

I am using Visual Studio Code to replace text with Python. I am using a source file with original text and converting it into a new file with new text.

I would like to add quotes to the new text that follows. For example:

Original text: set vlans xxx vlan-id xxx

New text: vlan xxx name "xxx" (add quotes to the remaining portion of the line as seen here)

Here is my code:

    with open("SanitizedFinal_E4300.txt", "rt") as fin:
        with open("output6.txt", "wt") as fout:
            for line in fin:
                     line = line.replace('set vlans', 'vlan').replace('vlan-id', 'name')
                     fout.write(line)

Is there a way to add quotes for text in the line that follows 'name'?

Edit:

I tried this code:

    with open("SanitizedFinal_E4300.txt", "rt") as fin:
    with open("output6.txt", "wt") as fout:
    for line in fin:
     line = line.replace('set vlans', 'vlan').replace('vlan-id', 'name')
     words = line.split()
        words[-1] = '"' + words[-1] + '"'
        line = ' '.join(words)
     fout.write(line)

and received this error:

line 124, in <module>
words[-1] = '"' + words[-1] + '"'
IndexError: list index out of range

I also tried this code with no success:

    with open("SanitizedFinal_E4300.txt", "rt") as fin:
    with open("output6.txt", "wt") as fout:
    for line in fin:
    line = line.replace('set vlans', 'vlan').replace('vlan-id', 'name')
    
    import re
        t = 'set vlans xxx  vlan-id xxx'
        re.sub(r'set vlans(.*)vlan-id (.*)', r'vlan\1names "\2"', t)
        'vlan xxx  names "xxx"'

Again, my goal is to automatically add double quotes to the characters (vlan numbers) at the end of a line.

For example:

Change this: set vlans default vlan-id 1

Into this: vlan default name "1"



from Recent Questions - Stack Overflow https://ift.tt/3AqrcyX
https://ift.tt/eA8V8J

No comments:

Post a Comment