0

12347 10000 secretary James Harrison
12348 20000 secretary Jade Powell
12341 40000 consultant Adam Johnson

Hi, lets just say that the text above is a text file. How would I go about searching and printing the rows with 'secretary' only? Or any other value? When the user is asked to input a word to search

The code below prints out everything in a file:

f = open("a text file", "r");

print(f.read())

print(f.readline())

myLines = f.readlines()

for line in myLines:
    print(line)
2
Contributors
2
Replies
9
Views
4 Years
Discussion Span
Last Post by TeaAnyOne
1

Here is one example ...

'''
show only the data lines that contain the search word
'''

# test data string
data = '''\
12347 10000 secretary James Harrison
12348 20000 secretary Jade Powell
12341 40000 consultant Adam Johnson'''

# pick a somewhat unique file name
fname = "aaatest123.txt"

# write out the data file
with open(fname, "w") as fout:
    fout.write(data)

search = 'secretary'

# read the data back in
with open(fname, "r") as fin:
    mylist = []
    for line in fin:
        line = line.rstrip()
        if search in line:
            mylist.append(line)

print(mylist)

'''result ...
['12347 10000 secretary James Harrison', '12348 20000 secretary Jade Powell']
'''

You can refine this to make it case insensitive or whole words only.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.