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)

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.

Thanks alot buddy! :D

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.