Skip to main content
 首页 » 编程设计

Python:在文件中搜索字符串

2024年10月01日30youxin

我正在尝试在包含多个日期的文件中搜索今天的日期 (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