Reading from a File Based on String Input

Question:

I’m trying to convert a Perl program over to Python.

What I would like to have happen is for the input to be read, and then the matching output comes out from the file based on the string.

So far, this is what I’ve tried (for this particular function):

def SunSign():

    print ("nnYou want to know more about your Sun Sign!n")
    print ("Your sun sign is your core identity and probably the sign that you are most familiar with as it is your zodiac!nn")

    sun = input("What is your Sun Sign?n")

    with open("sunsigns.txt", "r") as file:

        content = file.read()

        if sun in content:
            print(sun)

    Restart()

I realize that the variable I have printing is not what I need. That’s the part I need assistance on figuring out. If I switch out sun with content, it will print out the whole file.

Asked By: Alyssa St. Don

||

Answers:

You can go through the file line by line, then print the line that contains the sign you’re looking for:

with open('sunsigns.txt','r') as f:
   for line in f:       
       if sun in line:
          print(line)

Answered By: afarrag
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.