我試圖在填充了多個日期的文件上搜索今天的日期(2017-05-03)。如果在文件中找到日期,則返回true並繼續執行腳本,如果不是,則結束執行。Python:在文件上搜索字符串
這裏是我的示例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文件。我不知道我做錯了什麼。
那是快,感謝分享知識和幫助我! – Luiz
總是樂於提供幫助。 –