2017-05-03 4 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

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

관련 문제