Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reading from a File Based on String Input

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def SunSign():

    print ("\n\nYou 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!\n\n")

    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.

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading