Reputation: 151
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.
Upvotes: 2
Views: 83
Reputation: 5533
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
Upvotes: 0
Reputation: 4282
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
Upvotes: 2