user3843433
user3843433

Reputation: 189

python no idea what's wrong

I want write a function to achieve open a file->choose a certain column->take out the non repeated names->write the names into another file. I have written some code like this:

def method2(filename):
    name = filename + '.txt'
    content = open(name,'r')

    for line in content:
        values = line.split()
        a = values[1]

        print(a)

the error is:

>>> method2('test')
d8:c7:c8:5e:7c:2d,
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    method2('test')
  File "C:/Users/Yifan/Desktop/data/Training data/Method2.py", line 10, in method2
    a = values[1]
IndexError: list index out of range

my file looks like this:

  1405684432,        d8:c7:c8:5e:7d:e8,          SUTD_Guest,   57



  1405684432,        d8:c7:c8:5e:7c:89,           SUTD_ILP2,   74



  1405684432,        d8:c7:c8:5e:7c:8d,           SUTD_GLAB,   74



  1405684432,        b0:c5:54:dc:dc:6c,              ai-ap1,   85

Upvotes: 0

Views: 89

Answers (2)

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 3818

Here you go

test.py

def read_file(filename):
    file = open(filename)
    contents = map(str.strip,file.readlines())
    file.close()
    return contents

def get_column_values(col_num,lines):
    column_values = []

    for line in lines:
        if not line:
            continue

        values = line.split()

        #col_num - 1 = index of list
        #[:-1] will chop the last char i.e. comma from the string
        column_values.append(values[col_num-1][:-1])

    return column_values

def remove_duplicates(xList):
    return list(set(xList))


def write_file(filename,lines):
    file = open(filename,"w")
    for line in lines:
        file.write("%s\n" % line)
    file.close()


def main():
    lines = read_file("input.txt")

    #Work on 1st Column i.e. 0th index
    column_values = get_column_values(1,lines)
    entries = remove_duplicates(column_values)
    write_file("output.txt",entries)

main()

input.txt

1405684432,        d8:c7:c8:5e:7d:e8,          SUTD_Guest,   57

1405684432,        d8:c7:c8:5e:7c:89,           SUTD_ILP2,   74

1405684432,        d8:c7:c8:5e:7c:8d,           SUTD_GLAB,   74

1405684432,        b0:c5:54:dc:dc:6c,              ai-ap1,   85

output.txt 1405684432

Upvotes: 2

Joe
Joe

Reputation: 47609

When you reach the second line, which looks empty, and split it, you only get an empty list in values. Trying to access element 1, i.e. the second, fails, because there is no second element.

Try putting if len(values) > 0: in there to protect a = line[1].

Upvotes: 3

Related Questions