Python Forum

Full Version: Print multiple record lines
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am creating a simple program that looks up the name of a job and prints out the full job name and number.

I want to be able to put in partial string and have the program print any job name that has that string.

ie. user enters "short"
program prints "Short North Phase 3 - 2016-0401"
"Short North Phase 2 - 2016-0405"
"Short North Public Outreach - 2016-0551"

I am stuck on the printing multiple lines that match the input string.
here is my current code:

while True:
    jobname=input("Please enter job name")
    jobname=jobname.upper()



    jobs = open("jobs.txt")
    for line in jobs:
        record = line.split('|')
        if jobname in record[0]:
            found = True
            break
        else:
            found = False
            continue

    if found == False:
        print("Job name not found")
    else:
        print(record[0], record[1])
any help would be greatly appreciated.
Instead of breaking when you find a match, maybe keep a list of matches?
matches = []
with open("jobs.txt") as jobs:
    for line in jobs:
        record = line.split("|")
        if jobname in record[0]:
            matches.append(record)
if matches:
    for record in matches:
        print(record[0], record[1])
else:
    print("Job name not found")
That is genius. Works perfectly.
You can also make a generator, which is cool :p
If your jobs file is massive, and you could potentially have millions of matches, this is something similar to what you'd want to be using.

def find_within(haystack, match, processor=None):
    with open(haystack) as file:
        for line in file:
            if processor:
                line = processor(line)
            if match(line):
                yield line

matches = find_within("jobs.txt",
    lambda job: job[0] == jobname,
    lambda line: line.split("|"))

for match in matches:
    print(match[0], match[1])