Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.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
Python:在文件中搜索字符串_Python_Search - Fatal编程技术网

Python:在文件中搜索字符串

Python:在文件中搜索字符串,python,search,Python,Search,我试图在一个包含多个日期的文件中搜索今天的日期(2017-05-03)。如果在文件中找到日期,则返回true并继续脚本,否则结束执行 这是我的示例days.txt文件: 2017-05-01 2017-05-03 2017-04-03 这是我的剧本: # Function to search the file def search_string(filename, searchString): with open(filename, 'r') as f: for lin

我试图在一个包含多个日期的文件中搜索今天的日期(2017-05-03)。如果在文件中找到日期,则返回true并继续脚本,否则结束执行

这是我的示例
days.txt
文件:

2017-05-01
2017-05-03
2017-04-03
这是我的剧本:

# Function to search the file
def search_string(filename, searchString):
    with open(filename, 'r') as f:
        for line in f:
            return searchString in line

# Getting today's date and formatting as Y-m-d
today = str(datetime.datetime.now().strftime("%Y-%m-%d"))

# Searching the script for the date
if search_string('days.txt', today):
    print "Found the date. Continue script"
else:
    print "Didn't find the date, end execution"

然而,它总是返回False,即使日期出现在我的txt文件中。我不知道我做错了什么。

您的函数只测试了第一行,因此只有在第一行包含字符串时才会返回True。应该是:

def search_string(filename, searchString):
    with open(filename, 'r') as f:
        for line in f:
            if searchString in line:
                return True
    return False

您过早地从搜索中返回

修复

# Function to search the file
def search_string(filename, searchString):
    with open(filename, 'r') as f:
        for line in f:
            if searchString in line: 
                return True
    return False

这很快,谢谢你分享知识和帮助我!总是很乐意帮忙。谢谢你的帮助。必须接受上面的答案,因为它更快。@Luiz没问题。