tags:

views:

65

answers:

2

This is the code I am working with that comes from Practical Programming:

 import sys

def process_file(filename):
 '''Open, read, and print a file.'''

 input_file = open(filename, "r")
 for line in input_file:
  line = line.strip()
  print line
 input_file.close()
 if __name__ == "__main__":
  process_file(sys.argv[1])

After import this module in IDLE and pass a text file argument through process_file(), I receive this error:

    Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    process_file("data.txt")
  File "C:\Python26\read_file_2.py", line 14, in process_file
    process_file(sys.argv[1])
IndexError: list index out of range

How can I get this program to work without receiving this error? Any help is appreciated.

A: 

you should move

if __name__ == "__main__":
    process_file(sys.argv[1])

out of the process_file function. When importing into IDLE make sure process_file is available and pass file name to it.

SilentGhost
A: 

It looks like you've got the

if __name__ == "__main__":
  process_file(sys.argv[1])

block at the same indentation level as the rest of the process_file definition, so it's being run when you call process_file from another module. I suspect that might be causing your problem - unindent it so the if is in line with the def.

Chris
This removes the error when I run this program from the command line, but does nothing for the problem in IDLE(which I am not that worried about).
Timmay
So what _is_ the problem in IDLE? If you've stepped that back out, you can't hit it when you call through.
Chris
IDLE still gives the list index out of range error when I pass the .txt file through process_file().
Timmay
It... can't. There's no longer any list indexing going on in that function. Have you made sure IDLE has reloaded the module since you changed it?
Chris