split() Error:list index out of range

759 views Asked by At
line = "2013/12/10@19:48:25"
datetime = line.split('@')
print datetime[1]

Whenever my program runs, it gets an error. I dont know why. but whenever i check the datetime variable it contains this ['2013/12/10', '19:48:25] which is correct. But I cant access the second element with datetime[1] it gives me an error of index out of bounds but i can access datetime[0]. Can someone tell me what im doing wrong? pls help, im confused and running out of patience. Thanks!

EDIT: so here is the real code

def setTimeStamp(line,newline):
    line = line.replace("[" , "")
    line = line.replace("]", "")

    datetime = line.split('@')

    print datetime[0] #this works fine
    #output sample: 2013/12/14
    print datetime[1] #this is getting an error

def main():
    newline = ''
    cg = open('log.lg','r')
    for line in cg:

        line = line.strip()
        parsed_line = line.split(" ")


        print parsed_line[0] 
        # output sample: [2013/12/14@08:45:13.296+0800]
        setTimestamp(parsed_line[0], newline)]'

so far this is what I am doing. After I figure out whats wrong with the code Ill move on, thats why the program looks pointless as of now.

2

There are 2 answers

0
OrdinaryProgrammer On BEST ANSWER

For those of you who are still looking for the answer or odded out by why I was getting an error, it was because the file format of a log file is in UNIX text file format. Hence, the python parser will be confused with some hidden special characters while parsing. I solved this issue after converting the log file from unix to dos using the 'unix2dos ' command in linux. After this, my parser worked smoothly.

0
dlask On

The code itself seems correct but you can add a couple of asserts to be sure that everything goes as expected.

line = "2013/12/10@19:48:25"
assert "@" in line          # check that "@" is present there
datetime = line.split('@')
assert len(datetime) == 2   # check that there are 2 elements
print datetime[1]           # then it's safe to take the second element

By the way, it would be reasonable to use a different name instead of datetime to avoid potential problems caused by hiding the datetime module name.