Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python2.7.8用于行迭代错误_Python_Python 2.7 - Fatal编程技术网

Python2.7.8用于行迭代错误

Python2.7.8用于行迭代错误,python,python-2.7,Python,Python 2.7,我想用下面的脚本遍历文件中的所有行 import sys infile = open("test.txt") infile.read() for line in infile if line.find("This") != -1 print line infile.close() 不幸的是,我收到了以下错误消息: File "getRes.py", line 6 for line in infile ^ Syn

我想用下面的脚本遍历文件中的所有行

import sys

infile = open("test.txt")
infile.read()

for line in infile
    if line.find("This") != -1
        print line

infile.close()
不幸的是,我收到了以下错误消息:

  File "getRes.py", line 6
    for line in infile
                     ^
SyntaxError: invalid syntax
我已经试了一个小时来找出错误是什么,但仍然找不到。你能告诉我什么地方出了问题,怎么解决吗


PS:我正在使用Python 2.7.8,我想使用这个旧版本而不是更新的版本。

在Python中引入块的任何行后面都需要一个冒号

for line in infile:
    if line.find("This") != -1:

您的代码中还有一个错误,您不需要:

infile.read()
因为它读取infle的所有内容,而不将其保存到任何变量。更重要的是,它将您移动到文件的末尾,这样就没有更多的行可读了

此外,无需手动关闭文件,最好与语句一起使用:

with open("test.txt") as infile:
    for line in infile:
        # do what you want
# here file will be close automaticaly, when we exit "with" scope.

这意味着您在infle之后缺少一个冒号,对于infle中的行,它应该是