-1

I am teaching myself python. I am trying read an input file using:

import numpy as np

import matplotlib.pyplot as plt

import math

import sys

NEM_2D = []

NEM_zdim = []
NEMdataline = False

with open(sys.argv[1],'r') as file:
    for line in file:

        single=line.split()

        if not line.startswith("!") and NEMdataline == True:
            if single[0].isdigit:
                NEM_X=[]
                for i in range(0,NEM_X):
                    if int(single[i]) == 0:
                        NEM_X.append(0)
                    if int(single[i]) == 1:
                        NEM_X.append(1)
                    if int(single[i]) != 0 and int(single[i]) != 1:
                        NEM_X.append(2)
                NEM_2D.append(2)         

file.close()

When I run, I find the following error message: with open(sys.argv[1],'r') as file:

IndexError: list index out of range

Barbara
  • 11
  • What do you run exactly ? `sys.argv` is option inputted in command line when running the script. If you run the script without any option sys.argv will be empty – Clément May 06 '20 at 14:25
  • 2
    Welcome to Stack Overflow. Did you already take the [tour] and learn [how to ask a question](https://stackoverflow.com/help/how-to-ask)? It will help you use the site more effectively and get better responses. – wovano May 06 '20 at 14:27
  • 1
    Does this answer your question? [sys.argv\[1\] meaning in script](https://stackoverflow.com/questions/4117530/sys-argv1-meaning-in-script) – Tomerikoo May 06 '20 at 14:34

1 Answers1

1

This error means that sys.argv does not have a second element in the list (lists are 0-indexed, so the first element has an index of 0, and the second has an index of 1, etc.). Wherever you are running your Python script from, you need to pass a command-line argument so that sys.argv[1] has a value: python script.py <filename>. Now if you use sys.argv[1], it will contain whatever value you pass in as the filename. Note that sys.argv[0] contains the name of the script itself

Also, you can remove the file.close() line because using a with block handles closing the file for you

awarrier99
  • 3,628
  • 1
  • 12
  • 19