h1h1
h1h1

Reputation: 780

Python - Searching Text File for String

I have the following function that takes 3 pieces of information (name, age, hometown) for 3 people and saves it in a txt file.

def peopleInfo():
    txtFile = open("info.txt", "w")
    i = 0
    for i in range(0, 3):
        name = input("Enter name ")
        age = input("Enter age ")
        hometown = input("Enter hometown ")
        txtFile.write(name + "\n" + age + "\n" + hometown + "\n")
    txtFile.close()

I am now trying to create a function that will read the text file and print a persons name if their hometown is 'Oxford'. So far I have the following just to read the text from the file but im not sure how to skip back a line and print the name if the town is Oxford.

def splitLine():
    txtFile = open("info.txt", "r")
    for line in txtFile:
        line = line.rstrip("\n")
        print(line)

Thanks for any help!

Upvotes: 1

Views: 16332

Answers (1)

h1h1
h1h1

Reputation: 780

I used the following for anyone that is interested:

def peopleInfo():
    txtFile = open("info.txt", "w")
    i = 0
    for i in range(0, 3):
        name = input("Enter name ")
        age = input("Enter age ")
        hometown = input("Enter hometown ")
        txtFile.write(name + "\n" + age + "\n" + hometown + "\n")
    txtFile.close()

def splitLine():
    txtFile = open("info.txt", "r")
    lineList = []
    i = 0
    for line in txtFile:
        lineList.append(line.rstrip("\n"))
        if "Oxford" in lineList[i]:
            print(lineList[i - 2])
        i += 1

Upvotes: 2

Related Questions