我正在编写一个程序来读取应输入正确数字时应打印邮政编码位置的邮政编码文本文件。但是,我在编写错误消息时遇到了问题。我已经尝试了各种方法并不能得到错误信息打印,这里是我有:搜索文件输入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