AndrewSwanson94 AndrewSwanson94 - 23 days ago 8
Python Question

Search file for input Python

I am writing a program to read a text file of zip codes that should print the location of the zip code when the correct number is input. However, I am having trouble writing the error message. I have tried various methods and cannot get the error message to print, here is what I have:

try:
myFile=open("zipcodes.txt") #Tries to open file user entered
except:
print "File can't be opened:", myFile #If input is invalid filename, print error
exit()

zipcode = dict() #List to store individual sentences
line = myFile.readline() #Read each line of entered file

ask = raw_input("Enter a zip code: ")

if ask not in line:
print "Not Found."
else:
for line in myFile:
words = line.split()
if words[2] == ask:
zipcode = words[0:2]
for value in zipcode:
print value,


Some sample ZIP codes:

Abbeville AL 36310
Abernant AL 35440
Acmar AL 35004
Adamsville AL 35005
Addison AL 35540
Adger AL 35006
Akron AL 35441
Alabaster AL 35007

Answer

From the beginning:

try:
    myFile=open("zipcodes.txt") 
except: 
    print "File can't be opened:", myFile # if open fail then myFile will be undefined.
    exit()

zipcode = dict() # you creating dict, but you never add something into it.

line = myFile.readline() # this will read only first line of file, not each

ask = raw_input("Enter a zip code: ") 

if ask not in line:  
    # it will print not found for any zipcode except zipcode in first line
    print "Not Found."
else:
    # because you already read 1 line of myFile
    # "for line in " will go from second line to end of file

    for line in myFile: # 1 line already readed. Continue reading from second 
       words = line.split() 
       if words[2] == ask: # If you don't have duplicate of first line this will never be True
          zipcode = words[0:2]

# So here zipcode is an empty dict. Because even if "ask is in line"
# You never find it because you don't check line 
# where the ask is (the first line of file).
for value in zipcode:
    # print never executed becouse zipcode is empty
    print value, 
Comments