MC Abstract
MC Abstract

Reputation: 37

How do I turn data from a text file into a list?

My objective here is to open the dog file, convert it into a list, and then let the user enter a type of dog and if it matches a dog name in the list, say it's correct.

dog_file = open("Dogs.txt", "r")
dogs = dog_file.readlines()
print(dogs)
data = input("Enter a name: ")
if data == dogs:
    print("Success")
else:
    print("Sorry that didn't work")

Upvotes: 1

Views: 98

Answers (4)

Aswini
Aswini

Reputation: 46

Try this:

dog_file = open("Dogs.txt", "r")
dogs = dog_file.readlines()
# you want to strip away the spaces and new line characters
content = [x.strip() for x in dogs]
data = input("Enter a name: ")
# since dogs here is a list
if data in dogs:
    print("Success")
else:
    print("Sorry that didn't work")

Upvotes: 1

Unusual Kmc
Unusual Kmc

Reputation: 47

If you want to write the .txt into an array (convert to list), try this:

with open("Dogs.txt", "r") as ins:
    dogarray = []
    for line in ins:
        line = line.strip()
        dogarray.append(line)
    print (dogarray)

This writes it into an array and uses the .strip function to remove the unwanted \n after every new line. All you need to do now is read from the array.

Upvotes: 1

GreenSaber
GreenSaber

Reputation: 1148

Try this:

dog_list = []
for dog in dogs:
    dog_list.append(dog)

This will append every line of the file into a list. Now to check if there is a dog in the list try:

dog_type = input("Enter a dog: ")
if dog_type in dog_list":
    print("Success")

Upvotes: 0

Leistungsabfall
Leistungsabfall

Reputation: 6488

dogs is a list of strings while data is a single string. You want to check if data is contained in dogs using the in operator:

if data in dogs:
    # do sth

Upvotes: 3

Related Questions