-3

I have a .txt file where names and addresses appear in the following format:

Sam, 35 Marly Road
...
...

I want to be able to search Sam and for 35 Marly Road to come up.

Here is the code I have so far:

name = input("Please insert your required Client's name: ")
if name in open('clientAddress.txt').read():
  print ("Client Found")`

This checks if the ID inputted is available in the file, but it doesn't print the address. How do I change it, so it finds the name and prints the address?

Dev-iL
  • 22,722
  • 7
  • 53
  • 89
A.Yasin
  • 1
  • 1
  • I've tried: open('clientRecords.txt').read(): print (" Found Client") But that only prints 'Found Client' and not the adress – A.Yasin Nov 28 '15 at 13:34
  • Consider taking a look at https://docs.python.org/2/library/csv.html combine reading the lines with an if statement that checks if it's the correct name and voila. – DJanssens Nov 28 '15 at 14:22
  • I don't need to check if it's the correct name- I've done that. I need my program to find the name in the file provided and print the address. – A.Yasin Nov 28 '15 at 14:27
  • That's what I mean by: 'checking if it's the correct name'. You'll need an ìf`statement that checks if the line has the same name as you expected. – DJanssens Nov 28 '15 at 15:31

2 Answers2

0

As a quick solution - see below

username = input()

with open('clientRecords.txt', 'r') as clientsfile:
    for line in clientsfile.readline():
        if line.startswith("%s, " % username):
            print("Cient %s found: %s" % (username, line[len(username) + 2:]))
            break
baldr
  • 2,514
  • 10
  • 37
  • 53
  • I tried that- and it didn't do anything. No matter what i typed in, it simply terminated the program. (Skipped to the next line and gave me >>>) – A.Yasin Nov 28 '15 at 14:10
0

Simple solution

username = input()
with open('clientRecords.txt', 'r') as clientsfile:
    for line in clientsfile:
        if line.startswith("%s, " % username):
            print("Client %s found: %s" % (username, line.split(",")[1]))
            break

For loop iterates through file lines and when we found line starts with desired client name we print address and break loop.

kvorobiev
  • 4,801
  • 4
  • 27
  • 33