繁体   English   中英

FileNotFoundError Try and except 似乎不起作用

[英]FileNotFoundError Try and Except seems to not be working

 def make_sender(self):
        a = False
        y = input("Make sender (Y/N)?")
        if y.lower() == "y":
            a = True
        while a == True:
            s = input("Enter folder name : ")
            t = input("Enter profile name: ")
            try:
                p = os.getcwd()+("\profiles")
                d = os.path.join(p, s,t)
                with open(d+".txt","w") as f:
                    print(">>> Opened ")
            except FileNotFoundError:
                print(">>> File not found ")
            
            with open(d+".txt","w") as f:
                temp = input("Full Name: ")
                temp = temp.title()
                f.write(temp+"\n")

                temp = input("House Number: ")
                f.write(temp+"\n")

                temp = input("Street Name : ")
                f.write(temp+"\n")
                
                temp = input("Postcode    : ")
                f.write(temp+"\n")

                temp = input("Email       : ")
                f.write(temp+"\n")
            a = False

认为我的代码会继续运行,直到输入正确的数据。 认为我的尝试和例外是错误的。 我得到了正确的除代码,但认为缩进或有什么问题。

您可以将 with 块移出循环或将其放在 else 块下。 首选将需要额外检查a (或者如果y.lower != 'y'在开始时更简单的return 。我认为以下方法更干净:

 def make_sender(self):
        y = input("Make sender (Y/N)?")
        while y.lower() == 'y':
            s = input("Enter folder name : ")
            t = input("Enter profile name: ")
            try:
                p = os.getcwd()+("\profiles")
                d = os.path.join(p, s,t)
                with open(d+".txt","w") as f:
                    print(">>> Opened ")
            except FileNotFoundError:
                print(">>> File not found ")
            else:
                with open(d+".txt","w") as f:
                    temp = input("Full Name: ")
                    temp = temp.title()
                    f.write(temp+"\n")

                    temp = input("House Number: ")
                    f.write(temp+"\n")

                    temp = input("Street Name : ")
                    f.write(temp+"\n")
                
                    temp = input("Postcode    : ")
                    f.write(temp+"\n")

                    temp = input("Email       : ")
                    f.write(temp+"\n")
                    
                break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM