pythontry-exceptgetopenfilename

Try and except trouble with practice problem getting error


Using try and except, open animals_shortList.txt for reading and read the file data, creating a new list. Sort the list alphabetically. it would look like this temporary. https://i.sstatic.net/A7TE9.jpg

Once the list has been successfully created and sorted, loop through each item in the list and prints the animal, phylum, and diet, as shown. Use a variable to number each printed line. it should be shown like this [1]: https://i.sstatic.net/e9Wi5.jpg

Code:

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()


Solution

  • Try it like this :

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