2017-05-03 32 views
2

私は、今日の日付(2017-05-03)をいくつかの日付が入ったファイルで検索しようとしています。ファイル上に日付が見つかった場合はtrueを返し、スクリプトを続行します。実行されていない場合は実行を終了します。Python:ファイル上の文字列を検索

は、ここに私のサンプルdays.txtファイルです:

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

これは私のスクリプトです:それは常に日が私のtxtファイルに存在する場合でも、Falseを返すしかし

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

。私は何が間違っているのか分からない。

答えて

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 
+1

! – Luiz

+0

常に喜んで助けてください。 –

0

You returnが早すぎる必要があります。 、その知識を共有し、私を助けてくれてありがとう速かった

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 
+0

ご協力ありがとうございます。それが速かったので、上記の答えを受け入れなければならなかった。 – Luiz

+0

@ルイズ問題ありません。 – luoluo

関連する問題