在文本文件中搜索字符串:名称未定义错误python3

时间:2016-05-11 22:42:15

标签: python

您好我想使用python搜索文本文件中的字符串。我正在使用python3。

这是我的代码: -

def check():
        datafile = open('testfile.txt')
        found = False
        for line in datafile:
            if good in line:
                found = True
                break

        return found

found = check()
if found:
    print ("String found")
else:
    print ("not found")

这里testfile.txt是一个文本文件,其中包含字符串" good"。因此,预期的输出应该是" String found"。但是,它显示错误" NameError:name' good'没有定义'。

3 个答案:

答案 0 :(得分:3)

由于您正在寻找字符串'good',因此您需要用引号括起来。现在,该程序认为您正在尝试查找存储在名为good的变量中的内容,并且该变量不存在。

if 'good' in line:

那应该解决你的问题。

编辑以回应评论: 您可以返回找到字符串的行,并将其添加到print语句中。

def check():
        datafile = open('testfile.txt')
        found = False
        for line in datafile:
            if 'good' in line:
                found = True
                break
        return found, line

found, line = check()
if found:
    print ("String found: " + line)
else:
    print ("not found")

答案 1 :(得分:0)

你忘记在你希望成为字符串的地方加上引号 将<?php define('IS_AJAX', true); $id = $db->real_escape_string($_GET['photo_id']); $files = $db->query("SELECT * FROM uploaded_photos WHERE id=".$id); $files = $files->fetch_object(); $file = $files->path; if($file){ unlink("../uploads/".$file); $db->query("DELETE FROM uploaded_photos WHERE id='".$id); } 更改为good'good'将解决您的问题。

此代码还存在其他一些问题,您忘记关闭该文件。
您的代码看起来应该更像:

"good"

如果您在IDE中编辑python(例如def check(): with open('testfile.txt') as datafile: found = False for line in datafile: if 'good' in line: found = True break return found ),您会发现这些错误更容易,因为语法突出显示通常会突出显示字符串,但不会突出显示变量名称。

答案 2 :(得分:0)

您可以使用x.find('my string')对象检查字符串并返回您要查找的子字符串的次数。如果它不存在它应该返回0.也许这是一个更加蟒蛇的方式这样做?希望这有助于=)