close

[Solved] sys.argv[1], Index: list index out of range

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error sys.argv[1], Index: list index out of range in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How sys.argv[1], Index: list index out of range Error Occurs?

Today I get the following error sys.argv[1], Index: list index out of range in python.

How To Solve sys.argv[1], Index: list index out of range Error ?

  1. How To Solve sys.argv[1], Index: list index out of range Error ?

    To Solve sys.argv[1], Index: list index out of range Error sys.argv[0] is the name of the script you are running. All additional options are contained in sys.argv[1:].

  2. sys.argv[1], Index: list index out of range

    To Solve sys.argv[1], Index: list index out of range Error sys.argv[0] is the name of the script you are running. All additional options are contained in sys.argv[1:].

Solution 1

sys.argv represents the command line options you execute a script with.

sys.argv[0] is the name of the script you are running. All additional options are contained in sys.argv[1:].

You are attempting to open a file that uses sys.argv[1] (the first argument) as what looks to be the directory.

Try running something like this:

python ConcatenateFiles.py /tmp

Solution 2


sys.argv
 is the list of command line arguments passed to a Python script, where sys.argv[0] is the script name itself.

It is erroring out because you are not passing any commandline argument, and thus sys.argv has length 1 and so sys.argv[1] is out of bounds.

To “fix”, just make sure to pass a commandline argument when you run the script, e.g.

python ConcatenateFiles.py /the/path/to/the/directory

However, you likely wanted to use some default directory so it will still work when you don’t pass in a directory:

cur_dir = sys.argv[1] if len(sys.argv) > 1 else '.'

with open(cur_dir + '/Concatenated.csv', 'w+') as outfile:

    try:
        with open(cur_dir + '/MatrixHeader.csv') as headerfile:
            for line in headerfile:
                outfile.write(line + '\n')
    except:
        print 'No Header File'

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read