user5525947
user5525947

Reputation:

Reading data from files from a user input

So I have a text file that I've made up with a persons name followed by a comma and then a place where they could live. Yes I know its random but I need a way to understand this :)

So here is the text file (called "namesAndPlaces.txt"):

Bob,Bangkok
Ellie,London
Anthony,Beijing
Michael,Boston
Fred,Texas
Alisha,California

So I want the user to be able to enter a name into the program and then the program looks at the text file to see where they live and then prints it out to the user.

How can I do this? Thanks Michael

Upvotes: 0

Views: 98

Answers (2)

Mad Wombat
Mad Wombat

Reputation: 15105

A bit more pythonic way of doing the same thing Aneta suggested

with open(filename, 'r') as source:
    text = source.read()
    place_to_names = dict([line.split(r',') for line in text.split()])

while True:
    name = raw_input('Enter a name:')
    print("%s lives in %s" % (name, places_to_names[name]))

Upvotes: 0

leela.fry
leela.fry

Reputation: 299

I would do it this way:

text_file = open('pathtoFile', 'r').read()
text = text_file.split()

#turn the text into a dictionary
names_dic = []
for x in text:
    x = x.split(',')
    names_dic.append(x)

names_dic = dict(names_dic)

print names_dic  #for testing

# asking a user to enter a name
name = "not_in_dic"
while name not in names_dic:
    name = raw_input("Enter the name? ")
    print name, "lives in ", names_dic[name]

Upvotes: 1

Related Questions