Question

The .txt file contains 3 fields comma (,) seperated text, numbers and some special characters, running just a for row in sortedlist: print row[1] for example works fine.

import csv
import operator
import sys

inf = csv.reader(open('data.txt','r'))
sortedlist = sorted(inf, key=operator.itemgetter(2), reverse=True)

def dothis(x):
    for row in sortedlist:
        print row[x]

if __name__ == "__main__":
    c = sys.argv[0]
    if (c == ''):
        raise Exception, "missing first parameter - row"
    dothis(c)

I am receiving the following error -

python test.py 1 Traceback (most recent call last):   File "test.py", line 16, in ?
    dothis(c)   File "test.py", line 10, in dothis
    print row[x] TypeError: list indices must be integers

What am I doing wrong?

Était-ce utile?

La solution

In the code you show, c and therefore x are set to sys.argv[0], which is a string. You can't use a string to index into a list.

Did you mean to say:

if __name__ == "__main__":
    if len(sys.argv) < 2:
        raise Exception, "missing first parameter - row"
    c = int(sys.argv[1])
    dothis(c)

Autres conseils

Command line arguments are string by default even when they are a numbers. If you need to use it as the index of a list, you need to convert it to a number, possibly with int

Your case is even stranger, you are using sys.argv[0] to access the list as an index. Please remember, sys.argv[0], is always the name of the current executing script and would in all case be a non number, non integer. I believe by all cases you meant sys.argv[1] wherever you mentioned sys.argv[0]

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top