Python 2.7 python通过.txt文件执行open和for循环

Python 2.7 python通过.txt文件执行open和for循环,python-2.7,Python 2.7,**python新手,并没有发现这类代码的问题。 我试图一次读取另一个文本(infle)文件中的一行,当它到达第2行时,cmd会给我“语法错误” 我错过了什么** import sys with open(sys.argv[1],'r') as infile: lines = [] for line in infile: lines.append(line) while lines: print len(lines), ':', lines.pop()

**python新手,并没有发现这类代码的问题。 我试图一次读取另一个文本(infle)文件中的一行,当它到达第2行时,cmd会给我“语法错误”

我错过了什么**

import sys

with open(sys.argv[1],'r') as infile:
    lines = []
    for line in infile:
        lines.append(line)

while lines:
    print len(lines), ':', lines.pop(),

嗯,你在第二行中把
inflie
拼错为
inflile
,我在这里编辑文本时意外地把它修好了。谢谢如果您不知道为什么要使用它,您不应该将
一起使用。你知道为什么吗?你说的“第一行”是指“导入系统”行吗?这表明您的程序正在被Python以外的东西解释。我们建议使用“with”进行filestream处理,以执行open命令并分配给var。当代码块退出时,需要filestream自动关闭。您还推荐其他类似的方式吗?:)