process_file(sys.argv[1]) IndexError: 列表索引超出范围

发布于 2024-09-12 11:03:50 字数 715 浏览 2 评论 0原文

这是我正在使用的代码,来自实用编程:

 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心凉 2024-09-19 11:03:50

看起来您的

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

块与 process_file 定义的其余部分处于相同的缩进级别,因此当您从另一个模块调用 process_file 时它正在运行。我怀疑这可能会导致您的问题 - 取消缩进,以便 ifdef 保持一致。

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.

请持续率性 2024-09-19 11:03:50

您应该移出

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

process_file 函数。导入到 IDLE 时,请确保 process_file 可用并将文件名传递给它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文