我正在編寫一個程序來讀取應輸入正確數字時應打印郵政編碼位置的郵政編碼文本文件。但是,我在編寫錯誤消息時遇到了問題。我已經嘗試了各種方法並不能得到錯誤信息打印,這裏是我有:搜索文件輸入Python
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,
一些樣品郵政編碼:
Abbeville AL 36310
Abernant AL 35440
Acmar AL 35004
Adamsville AL 35005
Addison AL 35540
Adger AL 35006
Akron AL 35441
Alabaster AL 35007
你可以添加 「zipcodes.txt」 的部分質疑?前三條線就足夠了。 – Arnial
代碼下面有一些樣本。 – AndrewSwanson94
'readline'方法只讀取1行。我需要'讀''的東西。 – Arnial