Python try except in while loop

Cager
while True:
    print "Unesite ime datoteke kojoj zelite pristupiti."
    try:
        ime = raw_input("")
        printaj = open(ime, "r")
        print "Ovo su informacije ucenika %s." % (ime)
        print printaj.read()
    except:
        print "Datoteka %s ne postoji." % (ime)
    printaj.close()

This program is supposed to look for a file, open and read it if it exists.

So I open program, try to look for a file lets say under name "John" but it doesn't exist so program closes even its in a while loop. When I look for a file and it exists, it's information is printed and my program works as intended.

From there I can look for a file that doesn't exist and it prints out Datoteka %s ne postoji. like I wanted. So problem here is the first file name I look up for in a program. If its correct than good... program will function from there.

But if its wrong ... program just closes and you have to open program again.

DYZ

When the file does not exist, it cannot be opened. The variable printaj is not initialized. printaj.close() causes a NameError, and the program crashes. Possible solutions:

  • Move printaj.close() into the try block of your code, just after printaj.read()
  • Use with open(ime, "r") as printaj, it will close the file automatically (kindly suggested in the comments)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related