process_file(sys.argv[1]) IndexError: 列表索引超出范围
这是我正在使用的代码,来自实用编程:
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])
在 IDLE 中导入此模块并通过 process_file() 传递文本文件参数后,我收到此错误:
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 receive this error?任何帮助表示赞赏。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来您的
块与 process_file 定义的其余部分处于相同的缩进级别,因此当您从另一个模块调用 process_file 时它正在运行。我怀疑这可能会导致您的问题 - 取消缩进,以便
if
与def
保持一致。It looks like you've got the
block at the same indentation level as the rest of the
process_file
definition, so it's being run when you callprocess_file
from another module. I suspect that might be causing your problem - unindent it so theif
is in line with thedef
.您应该移出
process_file
函数。导入到 IDLE 时,请确保 process_file 可用并将文件名传递给它。you should move
out of the
process_file
function. When importing into IDLE make sureprocess_file
is available and pass file name to it.