Anh Phan
Anh Phan

Reputation: 15

Question regarding to reading a file into a list in Python

Click here to see a screenshot of the files. I am writing a program that reads 2 text files into a list, then ask the user to enter a name to check if it is a popular name or not. Here's what I've done so far:

girlFile = open('GirlNames.txt', 'r')
girlTexts = girlFile.readlines()
boyFile = open('BoyNames.txt', 'r')
boyTexts = boyFile.readlines()


choice = input("What gender do you want to enter: boy, girl, or both? ")

if choice == "boy":
    boyName = input("What is the boy's name? ")
    if boyName in boyTexts:
        print(boyName,"was a popular boy's name between 2000 and 2009.")
    else:
        print(boyName,"was not a popular boy's name between 2000 and 2009.")
elif choice == "girl":
    girlName = input("What is the girl's name? ")
    if girlName in girlTexts:
        print(girlName,"was a popular girl's name between 2000 and 2009.")
    else:
        print(girlName,"was not popular girl's name between 2000 and 2009.")
elif choice == "both":
    boyName = input("What is the boy's name? ")
    girlName = input("What is the girl's name? ")
    if boyName in boyTexts:
        print(boyName,"was a popular boy's name between 2000 and 2009.")
    else:
        print(boyName,"was not popular boy's name between 2000 and 2009.")
    if girlName in girlTexts:
        print(girlName,"was a popular girl's name between 2000 and 2009.")
    else:
        print(girlName,"was not a popular girl's name between 2000 and 2009.")
else:
    print("Invalid input, please restart the program.")

Although the program still works, I can't get any outputs beside "(that name) was not a popular name..." and I think my problem is about reading the file into the list, or may be I can't find that name in the list because of the code. For example, if I enter boy first, it will ask me the name of the boy you want to find, and if I enter Jacob, whose name is in the text file, it will print out that ("Jacob was a popular boy's name between 2000 and 2009."), otherwise, printing out that it wasn't.

Upvotes: 1

Views: 75

Answers (2)

Joshua Hall
Joshua Hall

Reputation: 342

You never stripped the \n newline characters from your list items. You can use something like this...

with open("BoyNames.txt", "r") as f:
    lines = f.readlines()
    name = input("What is the boy's name? ")
    for line in lines:
        if name == line.strip("\n"):
            print(f"{name} was a popular boy's name between 2000 and 2009.")

Upvotes: 1

Holden
Holden

Reputation: 642

So when there is a new line in a return file, in the readlines variable a \n is added to the text for that line. These can be removed with a loop and the rstrip function

boyFile = open('BoyNames.txt', 'r')
boyTexts = boyFile.readlines()
boyTexts = [name.rstrip('\n') for name in boyTexts]

Upvotes: 1

Related Questions