-1

So im trying to find a way so I can read a txt file and find a specific word. I have been calling the file with

myfile=open('daily.txt','r')

r=myfile.readlines()

that would return a list with a string for each line in the file, i want to find a word in one of the strings inside the list.

edit: Im sorry I meant if there was a way to find where the word is in the txt file, like x=myfile[12] x=x[2:6]

Ethoe
  • 3
  • 2
  • 2
    possible duplicate of [Finding the index of an item given a list containing it in Python](http://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python) – APerson Oct 24 '14 at 02:28
  • 2
    why all the thumbs down for answers? – jean Oct 24 '14 at 02:31
  • 1
    @jean It appears that some person or persons don't like it when bad or poorly-expressed questions are answered. I get where they're coming from, but it can seem harsh. – PM 2Ring Oct 24 '14 at 02:52
  • see: http://stackoverflow.com/questions/5319922/python-check-if-word-is-in-a-string and http://stackoverflow.com/questions/3893885/cheap-way-to-search-a-large-text-file-for-a-string – Paul Oct 24 '14 at 02:53

3 Answers3

1
with open('daily.txt') as myfile:
    for line in myfile:
        if "needle" in line:
            print "found it:", line

With the above, you don't need to allocate memory for the entire file at once, only one line at a time. This will be much more efficient if your file is large. It also closes the file automatically at the end of the with.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1
def findLines():
    myWord = 'someWordIWantToSearchFor'
    answer = []
    with open('daily.txt') as myfile:
        lines = myfile.readlines()
    for line in lines:
        if myWord in line:
            answer.append(line)
    return answer
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • Thanks, sorry I did not mention this in my main post but I want it to return where it found myWord – Ethoe Oct 24 '14 at 02:35
0

I'm not sure if the suggested answers solve the problem or not, because I'm not sure what the original proposer means. If he really means "words," not "substrings" then the solutions don't work, because, for example,

'cat' in line

evaluates to True if line contains the word 'catastrophe.' I think you may want to amend these answers along the lines of

 if word in line.split():  ...
saulspatz
  • 5,011
  • 5
  • 36
  • 47