2

I'm trying to search for today's date (2017-05-03) on a file populated with several dates. If the date is found on the file, then it returns true and continues the script, if not it ends the execution.

Here's my sample days.txt file:

2017-05-01
2017-05-03
2017-04-03

This is my script:

# 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"

However it always returns False, even if the date is present on my txt file. I don't know what I'm doing wrong.

2 Answers 2

2

Your function is testing only the first line, so it return True only if the first line contain your string. It should be :

def search_string(filename, searchString):
    with open(filename, 'r') as f:
        for line in f:
            if searchString in line:
                return True
    return False
Sign up to request clarification or add additional context in comments.

2 Comments

That was quick, thanks for sharing that knowledge and helping me out!
Always happy to help.
0

You return from the search too early.

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

2 Comments

Thanks for your help. Had to accept the answer above as it was faster.
@Luiz No problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.