Python:在fi上搜索字符串

2024-04-26 12:43:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个包含多个日期的文件中搜索今天的日期(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文件中。我不知道我做错了什么。你知道吗


Tags: 文件theintxtforsearchtodaydatetime
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

return太早从搜索中退出了。你知道吗

修复

# 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

相关问题 更多 >