Python try except in while循环

2024-06-26 14:30:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这个程序应该查找一个文件,如果它存在,打开并读取它。在

所以我打开程序,试着寻找一个文件,比如说“John”,但它不存在,所以程序甚至在while循环中关闭它。当我寻找一个文件并且它存在时,它的信息就会被打印出来,我的程序就可以正常工作了。在

从那里我可以寻找一个不存在的文件,它打印出Datoteka %s ne postoji.就像我想要的那样。 所以这里的问题是我在程序中查找的第一个文件名。 如果它是正确的而不是好的。。。程序将从此处运行。在

但如果它错了。。。程序刚关闭,你必须再次打开程序。在


Tags: 文件程序trueneprintwhileimedatoteka
1条回答
网友
1楼 · 发布于 2024-06-26 14:30:02

文件不存在时无法打开。变量printaj未初始化。printaj.close()导致NameError,程序崩溃。可能的解决方案:

  • printaj.close()移到代码的try块中,就在printaj.read()之后
  • 使用with open(ime, "r") as printaj,它将自动关闭文件(请在评论中建议)

相关问题 更多 >