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.
It looks like you’ve got the
block at the same indentation level as the rest of the
process_filedefinition, so it’s being run when you callprocess_filefrom another module. I suspect that might be causing your problem – unindent it so theifis in line with thedef.