Python:在文件上搜索字符串

时间:2017-05-03 12:48:12

标签: 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 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"

但是,即使我的txt文件中存在日期,它也始终返回False。我不知道自己做错了什么。

2 个答案:

答案 0 :(得分:2)

您的函数仅测试第一行,因此仅当第一行包含您的字符串时才返回True。它应该是:

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

答案 1 :(得分:0)

你过早地从搜索中return

FIX

# 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