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__":
p开发者_运维技巧rocess_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.
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
.
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.
精彩评论