Is there a way in python to look through a file line by line and find a word in that line, but only if the word is the first word in the line? Like if it was looking for the word "apple" then it would only notice if the line started with "apple", but not if "apple" was somewhere in the middle of the line.

Recommended Answers

All 3 Replies

Yes.

#!/usr/bin/env python

filename = '/home/david/Programming/Python/data.txt'

f = open(filename)
for line in f:
    if line.startswith('apple'):
        print line

Maybe this is too early, but generally the way after you become more familiar with the functions, you can start to use
generator expressions, which I love very much and looks often (but not always) more readable to me.

In my own idioms, giving maybe some ideas for future:

filename='data.txt' # I like file in same directory as code at least for testing
word = 'apple' # good practice to use variables, easy later to change to function parameters
with open(filename) as f: # with quarantees closing of file automatically
    # it is good to get in habit to use lower() when looking information
    # we just join the lines, they have newline at end allready
     print(''.join(line for line in f if line.lower().startswith(word)))
     # this print with single value in parenthesis works both in Python3 and Python2
commented: Thanks for the tips! +2

tonyjv

i admire your python skills
;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.