python-2.7splitshlex

shlex.split - list index out of range


I am currently trying to open a file and using shlex.split to segment the lines. Here is an example of 2 lines from the text file.

set group address "Untrust" "This is a test group"
set group address "Untrust" "This is a test group" add "Test-address"

When I run my code it says "IndexError: list index out of range". I do realize that this is because it doesn't recognize my linetoken[5]. Since both lines begin almost identical, how would I get the code to move beyond the first line and just go to the second. My current code is below. The user input and count are for entering zones and then having it loop through using the input zones, however, I erased most of the code in an attempt to fix this issue first.

import shlex
import sys

def main():
    zone = []
    zone = raw_input(str('enter zones: '))
    zone = shlex.split(zone)
    count = 0
    configfile = open('convert.txt','r')
    for configline in configfile:
        with open('converted.txt','a')
            linetoken = shlex.split(configline)
            if(linetoken[0]=='set' and linetoken[1]=='group' and linetoken[5]=='add'):
                converted.write(linetoken[0] +' ' +linetoken[1] +' ' +linetoken[2] +' ' +linetoken[3] +' ' +linetoken[4] +' ' +linetoken[5])
                break
main()

Solution

  • I figured out how the answer to my problem and so I figured I would post the solution. To get bypass the first line I had it check that the word 'add' wasn't in the linetoken. If this was true then I added the statement pass and continued to the elif statement. Below is my new code.

    import shlex
    import sys
    
    def main():
        zone = []
        zone = raw_input(str('enter zones: '))
        zone = shlex.split(zone)
        count = 0
        configfile = open('convert.txt','r')
        for configline in configfile:
            with open('converted.txt','a')
                linetoken = shlex.split(configline)
                if(linetoken[0]=='set' and linetoken[1]=='group' and 'add' not in linetoken):
                    pass
                elif(linetoken[0]=='set' and linetoken[1]=='group' and linetoken[5]=='add'):
                    converted.write(linetoken[0] +' ' +linetoken[1] +' ' +linetoken[2] +' ' +linetoken[3] +' ' +linetoken[4] +' ' +linetoken[5])
                    break
    main()