Try and except trouble with practice problem 获取错误

Try and except trouble with practice problem getting error

使用try和except,打开animals_shortList.txt读取文件数据,创建一个新列表。按字母顺序对列表进行排序。它看起来像这个临时的。 https://i.stack.imgur.com/A7TE9.jpg

列表成功创建和排序后,遍历列表中的每个项目并打印动物、门和饮食,如图所示。使用变量为每个打印行编号。它应该像这样显示 [1]: https://i.stack.imgur.com/e9Wi5.jpg

代码:

import sys
def main():

names = []

phylum = []

diet = []

output = ""

infile = "animals_shortList.txt"

try:

    animalFile = open(infile, "r")


except:

    print("Must be file", infile)

animalList = infile.readlines()

print(animalList)

fileName.close()

main()

像这样尝试:

infile = 'animals_shortList.txt'
try :
    with open (infile, 'r') as file :
        animalList = file.readlines ()
except :
    print ('Must be file ', infile)
print (animalList)