简体   繁体   中英

process_file(sys.argv[1]) IndexError: list index out of range

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.

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM